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
55,972
Add Import Directives to the VS options search text
Resolves https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1260748
JoeRobich
"2021-08-27T20:53:59Z"
"2021-08-31T18:50:41Z"
9ad67ca5b3931968c41bc88bddce4ffd696e807c
1f9bf9a09f12e4bcc3f1b4e1db861279e097eea5
Add Import Directives to the VS options search text. Resolves https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1260748
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenIfOperator.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenIfOperator Inherits BasicTestBase ' Conditional operator as parameter <Fact> Public Sub ConditionalOperatorAsParameter() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim a0 As Boolean = False Dim a1 As Integer = 0 Dim a2 As Long = 1 Dim b0 = a0 Dim b1 = a1 Dim b2 = a2 Console.WriteLine((If(b0, b1, b2)) &lt;&gt; (If(a0, a1, a2))) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ False ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 70 (0x46) .maxstack 3 .locals init (Boolean V_0, //a0 Integer V_1, //a1 Long V_2, //a2 Object V_3, //b1 Object V_4) //b2 IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: ldc.i4.1 IL_0005: conv.i8 IL_0006: stloc.2 IL_0007: ldloc.0 IL_0008: box "Boolean" IL_000d: ldloc.1 IL_000e: box "Integer" IL_0013: stloc.3 IL_0014: ldloc.2 IL_0015: box "Long" IL_001a: stloc.s V_4 IL_001c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean" IL_0021: brtrue.s IL_0027 IL_0023: ldloc.s V_4 IL_0025: br.s IL_0028 IL_0027: ldloc.3 IL_0028: ldloc.0 IL_0029: brtrue.s IL_002e IL_002b: ldloc.2 IL_002c: br.s IL_0030 IL_002e: ldloc.1 IL_002f: conv.i8 IL_0030: box "Long" IL_0035: ldc.i4.0 IL_0036: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectNotEqual(Object, Object, Boolean) As Object" IL_003b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0040: call "Sub System.Console.WriteLine(Object)" IL_0045: ret } ]]>).Compilation End Sub ' Function call in return expression <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub FunctionCallAsArgument() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim z = If(True, fun_Exception(1), fun_int(1)) Dim r = If(True, fun_long(0), fun_int(1)) Dim s = If(False, fun_long(0), fun_int(1)) End Sub Private Function fun_int(x As Integer) As Integer Return x End Function Private Function fun_long(x As Integer) As Long Return CLng(x) End Function Private Function fun_Exception(x As Integer) As Exception Return New Exception() End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 28 (0x1c) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call "Function C.fun_Exception(Integer) As System.Exception" IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000b: pop IL_000c: ldc.i4.0 IL_000d: call "Function C.fun_long(Integer) As Long" IL_0012: pop IL_0013: ldc.i4.1 IL_0014: call "Function C.fun_int(Integer) As Integer" IL_0019: conv.i8 IL_001a: pop IL_001b: ret }]]>) End Sub ' Lambda works in return argument <Fact()> Public Sub LambdaAsArgument_1() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim Y = 2 Dim S = If(True, _ Function(z As Integer) As Integer System.Console.WriteLine("SUB") Return z * z End Function, Y + 1) S = If(False, _ Sub(Z As Integer) System.Console.WriteLine("SUB") End Sub, Y + 1) System.Console.WriteLine(S) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 77 (0x4d) .maxstack 2 .locals init (Object V_0) //Y IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: stloc.0 IL_0007: ldsfld "C._Closure$__.$I0-0 As <generated method>" IL_000c: brfalse.s IL_0015 IL_000e: ldsfld "C._Closure$__.$I0-0 As <generated method>" IL_0013: br.s IL_002b IL_0015: ldsfld "C._Closure$__.$I As C._Closure$__" IL_001a: ldftn "Function C._Closure$__._Lambda$__0-0(Integer) As Integer" IL_0020: newobj "Sub VB$AnonymousDelegate_0(Of Integer, Integer)..ctor(Object, System.IntPtr)" IL_0025: dup IL_0026: stsfld "C._Closure$__.$I0-0 As <generated method>" IL_002b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0030: pop IL_0031: ldloc.0 IL_0032: ldc.i4.1 IL_0033: box "Integer" IL_0038: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object" IL_003d: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0042: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0047: call "Sub System.Console.WriteLine(Object)" IL_004c: ret } ]]>).Compilation End Sub ' Conditional on expression tree <Fact()> Public Sub ExpressionTree() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System Imports System.Linq.Expressions Module Program Sub Main(args As String()) Dim testExpr As Expression(Of Func(Of Boolean, Long, Integer, Long)) = Function(x, y, z) If(x, y, z) Dim testFunc = testExpr.Compile() Dim testResult = testFunc(False, CLng(3), 100) Console.WriteLine(testResult) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 100 ]]>).Compilation End Sub ' Conditional on expression tree <Fact()> Public Sub ExpressionTree_2() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer on Imports System Imports System.Linq.Expressions Module Program Sub Main(args As String()) Dim testExpr As Expression(Of Func(Of TestStruct, Long?, Integer, Integer?)) = Function(x, y, z) If(x, y, z) Dim testFunc = testExpr.Compile() Dim testResult1 = testFunc(New TestStruct(), Nothing, 10) Dim testResult2 = testFunc(New TestStruct(), 10, Nothing) Console.WriteLine (testResult1) Console.WriteLine (testResult2) End Sub End Module Public Structure TestStruct Public Shared Operator IsTrue(ts As TestStruct) As Boolean Return False End Operator Public Shared Operator IsFalse(ts As TestStruct) As Boolean Return True End Operator End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 10 0 ]]>).Compilation End Sub ' Multiple conditional operator in expression <Fact> Public Sub MultipleConditional() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim S = If(False, 1, If(True, 2, 3)) Console.Write(S) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 2 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 17 (0x11) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000b: call "Sub System.Console.Write(Object)" IL_0010: ret }]]>).Compilation End Sub ' Arguments are of types: bool, constant, enum <Fact> Public Sub EnumAsArguments() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim testResult = If(False, 0, color.Blue) Console.WriteLine(testResult) testResult = If(False, 5, color.Blue) Console.WriteLine(testResult) End Sub End Module Enum color Red Green Blue End Enum </file> </compilation>, expectedOutput:=<![CDATA[ 2 2 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000b: call "Sub System.Console.WriteLine(Object)" IL_0010: ldc.i4.2 IL_0011: box "Integer" IL_0016: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001b: call "Sub System.Console.WriteLine(Object)" IL_0020: ret }]]>).Compilation End Sub ' Implicit type conversion on conditional <Fact> Public Sub ImplicitConversionForConditional() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim valueFromDatabase As Object Dim result As Decimal valueFromDatabase = DBNull.Value result = CDec(If(valueFromDatabase IsNot DBNull.Value, valueFromDatabase, 0)) Console.WriteLine(result) result = (If(valueFromDatabase IsNot DBNull.Value, CDec(valueFromDatabase), CDec(0))) Console.WriteLine(result) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 0 0 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 60 (0x3c) .maxstack 2 .locals init (Object V_0) //valueFromDatabase IL_0000: ldsfld "System.DBNull.Value As System.DBNull" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldsfld "System.DBNull.Value As System.DBNull" IL_000c: bne.un.s IL_0016 IL_000e: ldc.i4.0 IL_000f: box "Integer" IL_0014: br.s IL_0017 IL_0016: ldloc.0 IL_0017: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToDecimal(Object) As Decimal" IL_001c: call "Sub System.Console.WriteLine(Decimal)" IL_0021: ldloc.0 IL_0022: ldsfld "System.DBNull.Value As System.DBNull" IL_0027: bne.un.s IL_0030 IL_0029: ldsfld "Decimal.Zero As Decimal" IL_002e: br.s IL_0036 IL_0030: ldloc.0 IL_0031: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToDecimal(Object) As Decimal" IL_0036: call "Sub System.Console.WriteLine(Decimal)" IL_003b: ret }]]>).Compilation End Sub ' Not boolean type as conditional-argument <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub NotBooleanAsConditionalArgument() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim x = 1 Dim s = If("", x, 2) 'invalid s = If("True", x, 2) 'valid s = If("1", x, 2) 'valid End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 36 (0x24) .maxstack 1 .locals init (Integer V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldstr "" IL_0007: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(String) As Boolean" IL_000c: pop IL_000d: ldstr "True" IL_0012: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(String) As Boolean" IL_0017: pop IL_0018: ldstr "1" IL_001d: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(String) As Boolean" IL_0022: pop IL_0023: ret }]]>).Compilation End Sub ' Not boolean type as conditional-argument <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub NotBooleanAsConditionalArgument_2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim x = 1 Dim s = If(color.Green, x, 2) Console.WriteLine(S) s = If(color.Red, x, 2) Console.WriteLine(s) End Sub End Module Public Enum color Red Blue Green End Enum </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 ]]>) End Sub <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact> Public Sub FunctionWithNoReturnType() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim x = 1 Dim s = If(fun1(), x, 2) End Sub Private Function fun1() End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 1 .locals init (Object V_0) //x IL_0000: ldc.i4.1 IL_0001: box "Integer" IL_0006: stloc.0 IL_0007: call "Function C.fun1() As Object" IL_000c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean" IL_0011: brtrue.s IL_001b IL_0013: ldc.i4.2 IL_0014: box "Integer" IL_0019: br.s IL_001c IL_001b: ldloc.0 IL_001c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0021: pop IL_0022: ret }]]>).Compilation End Sub ' Const as conditional- argument <WorkItem(541452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541452")> <Fact()> Public Sub ConstAsArgument() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Const con As Boolean = True Dim s1 = If(con, 1, 2) Console.Write(s1) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call "Sub System.Console.Write(Integer)" IL_0006: ret } ]]>).Compilation End Sub ' Const i As Integer = IF <Fact> Public Sub AssignIfToConst() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Const s As Integer = If(1>2, 9, 92) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Program.Main", <![CDATA[ { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }]]>).Compilation End Sub ' IF used in Redim <WorkItem(528563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528563")> <Fact> Public Sub IfUsedInRedim() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module Program Sub Main(args As String()) Dim s1 As Integer() ReDim Preserve s1(If(True, 10, 101)) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Program.Main", <![CDATA[ { // Code size 20 (0x14) .maxstack 2 .locals init (Integer() V_0) //s1 IL_0000: ldloc.0 IL_0001: ldc.i4.s 11 IL_0003: newarr "Integer" IL_0008: call "Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array" IL_000d: castclass "Integer()" IL_0012: stloc.0 IL_0013: ret }]]>).Compilation End Sub ' IF on attribute <Fact> Public Sub IFOnAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System &lt;Assembly: CLSCompliant(If(True, False, True))&gt; Public Class base Public Shared sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyDiagnostics() End Sub ' #const val =if <Fact> Public Sub PredefinedConst() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Public Class Program Public Shared Sub Main() #Const ifconst = If(True, 1, 2) #If ifconst = 1 Then #End If End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Program.Main", <![CDATA[ { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }]]>).Compilation End Sub ' IF as function name <Fact> Public Sub IFAsFunctionName() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Module M1 Sub Main() End Sub Public Function [if](ByVal arg As String) As String Return arg End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("M1.if", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }]]>).Compilation End Sub ' IF as Optional parameter <Fact()> Public Sub IFAsOptionalParameter() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Module M1 Sub Main() goo() End Sub Public Sub goo(Optional ByVal arg As String = If(False, "6", "61")) System.Console.WriteLine(arg) End Sub End Module </file> </compilation>, expectedOutput:="61").Compilation End Sub ' IF used in For step <Fact()> Public Sub IFUsedInForStep() CompileAndVerify( <compilation> <file name="a.vb"> Module M1 Sub Main() Dim s10 As Boolean = False For c As Integer = 1 To 10 Step If(s10, 1, 2) Next End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe) End Sub ' Passing IF as byref arg <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub IFAsByrefArg() CompileAndVerify( <compilation> <file name="a.vb"> Module M1 Sub Main() Dim X = "123" Dim Y = "456" Dim Z = If(1 > 2, goo(X), goo(Y)) End Sub Private Function goo(ByRef p1 As String) p1 = "HELLO" End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("M1.Main", <![CDATA[ { // Code size 26 (0x1a) .maxstack 1 .locals init (String V_0, //X String V_1) //Y IL_0000: ldstr "123" IL_0005: stloc.0 IL_0006: ldstr "456" IL_000b: stloc.1 IL_000c: ldloca.s V_1 IL_000e: call "Function M1.goo(ByRef String) As Object" IL_0013: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0018: pop IL_0019: ret }]]>) End Sub <WorkItem(541674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541674")> <Fact> Public Sub TypeConversionInRuntime() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections.Generic Public Class Test Private Shared Sub Main() Dim a As Integer() = New Integer() {} Dim b As New List(Of Integer)() Dim c As IEnumerable(Of Integer) = If(a.Length > 0, a, DirectCast(b, IEnumerable(Of Integer))) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseDll).VerifyIL("Test.Main", <![CDATA[ { // Code size 25 (0x19) .maxstack 2 .locals init (Integer() V_0, //a System.Collections.Generic.List(Of Integer) V_1) //b IL_0000: ldc.i4.0 IL_0001: newarr "Integer" IL_0006: stloc.0 IL_0007: newobj "Sub System.Collections.Generic.List(Of Integer)..ctor()" IL_000c: stloc.1 IL_000d: ldloc.0 IL_000e: ldlen IL_000f: conv.i4 IL_0010: ldc.i4.0 IL_0011: bgt.s IL_0016 IL_0013: ldloc.1 IL_0014: pop IL_0015: ret IL_0016: ldloc.0 IL_0017: pop IL_0018: ret } ]]>).Compilation End Sub <WorkItem(541673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541673")> <Fact> Public Sub TypeConversionInRuntime_1() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Public Interface IB Function f() As Integer End Interface Public Class AB1 Implements IB Public Function f() As Integer Implements IB.f Return 42 End Function End Class Public Class AB2 Implements IB Public Function f() As Integer Implements IB.f Return 1 End Function End Class Class MainClass Public Shared Sub g(p As Boolean) Dim x = (If(p, DirectCast(New AB1(), IB), DirectCast(New AB2(), IB))).f() End Sub Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("MainClass.g", <![CDATA[ { // Code size 29 (0x1d) .maxstack 1 .locals init (IB V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000a IL_0003: newobj "Sub AB2..ctor()" IL_0008: br.s IL_0011 IL_000a: newobj "Sub AB1..ctor()" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: callvirt "Function IB.f() As Integer" IL_0016: box "Integer" IL_001b: pop IL_001c: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInRuntime_2() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Public Interface IB Function f() As Integer End Interface Public Class AB1 Implements IB Public Function f() As Integer Implements IB.f Return 42 End Function End Class Class MainClass Public Shared Sub g(p As Boolean) Dim x = (If(p, DirectCast(New AB1(), IB), DirectCast(New AB1(), IB))).f() End Sub Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("MainClass.g", <![CDATA[ { // Code size 29 (0x1d) .maxstack 1 .locals init (IB V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000a IL_0003: newobj "Sub AB1..ctor()" IL_0008: br.s IL_0011 IL_000a: newobj "Sub AB1..ctor()" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: callvirt "Function IB.f() As Integer" IL_0016: box "Integer" IL_001b: pop IL_001c: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInRuntime_3() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Public Interface IB Function f() As Integer End Interface Public Class AB1 Implements IB Public Function f() As Integer Implements IB.f Return 42 End Function End Class Class MainClass Public Shared Sub g(p As Boolean) Dim x = (If(DirectCast(New AB1(), IB), DirectCast(New AB1(), IB))).f() End Sub Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("MainClass.g", <![CDATA[ { // Code size 28 (0x1c) .maxstack 2 .locals init (IB V_0) IL_0000: newobj "Sub AB1..ctor()" IL_0005: dup IL_0006: brtrue.s IL_0010 IL_0008: pop IL_0009: newobj "Sub AB1..ctor()" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: callvirt "Function IB.f() As Integer" IL_0015: box "Integer" IL_001a: pop IL_001b: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function m1() As IBase End Interface Class Derived Public Shared mask As Integer = 1 End Class Class Test1 Implements IBase Private y As IBase Private x As IBase Private cnt As Integer = 0 Public Sub New(link As IBase) x = Me y = link If y Is Nothing Then y = Me End If End Sub Public Shared Sub Main() End Sub Public Function m1() As IBase Implements IBase.m1 Return If(Derived.mask = 0, x, y) End Function 'version1 (explicit impl in original repro) Public Function m2() As IBase Return If(Derived.mask = 0, Me, y) End Function 'version2 End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.m1", <![CDATA[ { // Code size 21 (0x15) .maxstack 1 IL_0000: ldsfld "Derived.mask As Integer" IL_0005: brfalse.s IL_000e IL_0007: ldarg.0 IL_0008: ldfld "Test1.y As IBase" IL_000d: ret IL_000e: ldarg.0 IL_000f: ldfld "Test1.x As IBase" IL_0014: ret }]]>).VerifyIL("Test1.m2", <![CDATA[ { // Code size 16 (0x10) .maxstack 1 IL_0000: ldsfld "Derived.mask As Integer" IL_0005: brfalse.s IL_000e IL_0007: ldarg.0 IL_0008: ldfld "Test1.y As IBase" IL_000d: ret IL_000e: ldarg.0 IL_000f: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_1() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function m1() As IBase End Interface Class Derived Public Shared mask As Integer = 1 End Class Class Test1 Implements IBase Private y As IBase Private x As IBase Private cnt As Integer = 0 Public Sub New(link As IBase) x = Me y = link If y Is Nothing Then y = Me End If End Sub Public Shared Sub Main() End Sub Public Function m1() As IBase Implements IBase.m1 Return If(x, y) End Function 'version1 (explicit impl in original repro) Public Function m2() As IBase Return If(Me, y) End Function 'version2 End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.m1", <![CDATA[ { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "Test1.x As IBase" IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.0 IL_000b: ldfld "Test1.y As IBase" IL_0010: ret }]]>).VerifyIL("Test1.m2", <![CDATA[ { // Code size 12 (0xc) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_000b IL_0004: pop IL_0005: ldarg.0 IL_0006: ldfld "Test1.y As IBase" IL_000b: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_2() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function m1() As IBase End Interface Class Derived Public Shared mask As Integer = 1 End Class Class Test1 Implements IBase Private y As IBase Private x As IBase Private cnt As Integer = 0 Public Sub New(link As IBase) x = Me y = link If y Is Nothing Then y = Me End If End Sub Public Shared Sub Main() End Sub Public Function m1() As IBase Implements IBase.m1 Return If (x, DirectCast(y, IBase)) End Function 'version1 (explicit impl in original repro) Public Function m2() As IBase Return If (DirectCast(Me, IBase), y) End Function 'version2 End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.m1", <![CDATA[ { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "Test1.x As IBase" IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.0 IL_000b: ldfld "Test1.y As IBase" IL_0010: ret }]]>).VerifyIL("Test1.m2", <![CDATA[ { // Code size 12 (0xc) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_000b IL_0004: pop IL_0005: ldarg.0 IL_0006: ldfld "Test1.y As IBase" IL_000b: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_3() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections Imports System.Collections.Generic Class Test1 Implements IEnumerable Dim x As IEnumerator Dim y As IEnumerator Public Shared Sub Main() End Sub Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return If(Me IsNot Nothing, DirectCast(x, IEnumerator), DirectCast(y, IEnumerator)) End Function End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.GetEnumerator", <![CDATA[ { // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_000a IL_0003: ldarg.0 IL_0004: ldfld "Test1.y As System.Collections.IEnumerator" IL_0009: ret IL_000a: ldarg.0 IL_000b: ldfld "Test1.x As System.Collections.IEnumerator" IL_0010: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_4() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function GetEnumerator() As IBase End Interface Interface IDerived Inherits IBase End Interface Structure struct Implements IBase Public Shared Sub Main() End Sub Function GetEnumerator() As IBase Implements IBase.GetEnumerator Dim x As IDerived Dim y As IDerived Return If(x IsNot Nothing, DirectCast(x, IBase), DirectCast(y, IBase)) End Function End Structure </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("struct.GetEnumerator", <![CDATA[ { // Code size 9 (0x9) .maxstack 1 .locals init (IDerived V_0, //x IDerived V_1, //y IBase V_2) IL_0000: ldloc.0 IL_0001: brtrue.s IL_0005 IL_0003: ldloc.1 IL_0004: ret IL_0005: ldloc.0 IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: ret } ]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_5() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function GetEnumerator() As IBase End Interface Interface IDerived Inherits IBase End Interface Structure struct Implements IDerived Public Shared Sub Main() End Sub Function GetEnumerator() As IBase Implements IBase.GetEnumerator Dim x As IDerived Dim y As IDerived Return If(x IsNot Nothing, DirectCast(x, IDerived), DirectCast(y, IDerived)) End Function End Structure </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("struct.GetEnumerator", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 .locals init (IDerived V_0, //x IDerived V_1) //y IL_0000: ldloc.0 IL_0001: brtrue.s IL_0005 IL_0003: ldloc.1 IL_0004: ret IL_0005: ldloc.0 IL_0006: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_6() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Interface IBase Function GetEnumerator() As IBase End Interface Interface IDerived Inherits IBase End Interface Structure struct Implements IDerived Public Shared Sub Main() End Sub Function GetEnumerator() As IBase Implements IBase.GetEnumerator Dim x = GetInterface() Dim y = GetInterface() Dim z = If(x IsNot Nothing, DirectCast(x, IBase), DirectCast(y, IBase)) End Function Function GetInterface() As IBase Return Nothing End Function End Structure </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("struct.GetEnumerator", <![CDATA[ { // Code size 34 (0x22) .maxstack 1 .locals init (IBase V_0, //GetEnumerator Object V_1, //x Object V_2) //y IL_0000: ldarg.0 IL_0001: call "Function struct.GetInterface() As IBase" IL_0006: stloc.1 IL_0007: ldarg.0 IL_0008: call "Function struct.GetInterface() As IBase" IL_000d: stloc.2 IL_000e: ldloc.1 IL_000f: brtrue.s IL_0019 IL_0011: ldloc.2 IL_0012: castclass "IBase" IL_0017: br.s IL_001f IL_0019: ldloc.1 IL_001a: castclass "IBase" IL_001f: pop IL_0020: ldloc.0 IL_0021: ret }]]>).Compilation End Sub <Fact, WorkItem(545065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545065")> Public Sub IfOnConstrainedMethodTypeParameter() CompileAndVerify( <compilation> <file name="a.vb"> Friend Module BIFOpResult0011mod Public Sub scen7(Of T As Class)(ByVal arg As T) Dim s7_a As T = arg Dim s7_b As T = Nothing Dim s7_c = If(s7_a, s7_b) System.Console.Write(s7_c) End Sub Sub Main() scen7(Of String)("Q") End Sub End Module </file> </compilation>, expectedOutput:="Q").VerifyIL("BIFOpResult0011mod.scen7", <![CDATA[ { // Code size 30 (0x1e) .maxstack 2 .locals init (T V_0) //s7_b IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: initobj "T" IL_0009: dup IL_000a: box "T" IL_000f: brtrue.s IL_0013 IL_0011: pop IL_0012: ldloc.0 IL_0013: box "T" IL_0018: call "Sub System.Console.Write(Object)" IL_001d: ret }]]>) End Sub <Fact> Public Sub IfOnUnconstrainedMethodTypeParameter() CompileAndVerify( <compilation> <file name="a.vb"> Friend Module Mod1 Sub M1(Of T)(arg1 As T, arg2 As T) System.Console.WriteLine(If(arg1, arg2)) End Sub Sub M2(Of T1, T2 As T1)(arg1 as T1, arg2 As T2) System.Console.WriteLine(If(arg2, arg1)) End Sub Sub Main() M1(Nothing, 1000) M1(1, 1000) M1(Nothing, "String Parameter 1") M1("String Parameter 2", "Should not print") M1(Of Integer?)(Nothing, 4) M1(Of Integer?)(5, 1000) M2(1000, 6) M2(Of Object, Integer?)(7, Nothing) M2(Of Object, Integer?)(1000, 8) M2(Of Integer?, Integer?)(9, Nothing) M2(Of Integer?, Integer?)(1000, 10) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 0 1 String Parameter 1 String Parameter 2 4 5 6 7 8 9 10 ]]>).VerifyIL("Mod1.M1", <![CDATA[ { // Code size 22 (0x16) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: box "T" IL_0007: brtrue.s IL_000b IL_0009: pop IL_000a: ldarg.1 IL_000b: box "T" IL_0010: call "Sub System.Console.WriteLine(Object)" IL_0015: ret } ]]>).VerifyIL("Mod1.M2", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 IL_0000: ldarg.1 IL_0001: box "T2" IL_0006: brtrue.s IL_000b IL_0008: ldarg.0 IL_0009: br.s IL_0016 IL_000b: ldarg.1 IL_000c: box "T2" IL_0011: unbox.any "T1" IL_0016: box "T1" IL_001b: call "Sub System.Console.WriteLine(Object)" IL_0020: ret } ]]>) End Sub <Fact> Public Sub IfOnUnconstrainedTypeParameterWithNothingLHS() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Friend Module Mod1 Sub M1(Of T)(arg As T) Console.WriteLine(If(Nothing, arg)) End Sub Sub Main() ' Note that this behavior is different than C#'s behavior. This is consistent with Roslyn's handling ' of If(Nothing, 1), which will evaluate to 1 M1(1) Console.WriteLine(If(Nothing, 1)) M1("String Parameter 1") M1(Of Integer?)(3) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 1 1 String Parameter 1 3 ]]>).VerifyIL("Mod1.M1", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: box "T" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) End Sub <Fact> Public Sub IfOnUnconstrainedTypeParametersOldLanguageVersion() CreateCompilation( <compilation> <file name="a.vb"> Friend Module Mod1 Sub M1(Of T)(arg1 As T, arg2 As T) System.Console.WriteLine(If(arg1, arg2)) End Sub End Module </file> </compilation>, parseOptions:=TestOptions.Regular15_5).AssertTheseDiagnostics(<![CDATA[ BC36716: Visual Basic 15.5 does not support unconstrained type parameters in binary conditional expressions. System.Console.WriteLine(If(arg1, arg2)) ~~~~~~~~~~~~~~ ]]>) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenIfOperator Inherits BasicTestBase ' Conditional operator as parameter <Fact> Public Sub ConditionalOperatorAsParameter() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim a0 As Boolean = False Dim a1 As Integer = 0 Dim a2 As Long = 1 Dim b0 = a0 Dim b1 = a1 Dim b2 = a2 Console.WriteLine((If(b0, b1, b2)) &lt;&gt; (If(a0, a1, a2))) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ False ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 70 (0x46) .maxstack 3 .locals init (Boolean V_0, //a0 Integer V_1, //a1 Long V_2, //a2 Object V_3, //b1 Object V_4) //b2 IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: ldc.i4.1 IL_0005: conv.i8 IL_0006: stloc.2 IL_0007: ldloc.0 IL_0008: box "Boolean" IL_000d: ldloc.1 IL_000e: box "Integer" IL_0013: stloc.3 IL_0014: ldloc.2 IL_0015: box "Long" IL_001a: stloc.s V_4 IL_001c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean" IL_0021: brtrue.s IL_0027 IL_0023: ldloc.s V_4 IL_0025: br.s IL_0028 IL_0027: ldloc.3 IL_0028: ldloc.0 IL_0029: brtrue.s IL_002e IL_002b: ldloc.2 IL_002c: br.s IL_0030 IL_002e: ldloc.1 IL_002f: conv.i8 IL_0030: box "Long" IL_0035: ldc.i4.0 IL_0036: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectNotEqual(Object, Object, Boolean) As Object" IL_003b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0040: call "Sub System.Console.WriteLine(Object)" IL_0045: ret } ]]>).Compilation End Sub ' Function call in return expression <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub FunctionCallAsArgument() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim z = If(True, fun_Exception(1), fun_int(1)) Dim r = If(True, fun_long(0), fun_int(1)) Dim s = If(False, fun_long(0), fun_int(1)) End Sub Private Function fun_int(x As Integer) As Integer Return x End Function Private Function fun_long(x As Integer) As Long Return CLng(x) End Function Private Function fun_Exception(x As Integer) As Exception Return New Exception() End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 28 (0x1c) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call "Function C.fun_Exception(Integer) As System.Exception" IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000b: pop IL_000c: ldc.i4.0 IL_000d: call "Function C.fun_long(Integer) As Long" IL_0012: pop IL_0013: ldc.i4.1 IL_0014: call "Function C.fun_int(Integer) As Integer" IL_0019: conv.i8 IL_001a: pop IL_001b: ret }]]>) End Sub ' Lambda works in return argument <Fact()> Public Sub LambdaAsArgument_1() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim Y = 2 Dim S = If(True, _ Function(z As Integer) As Integer System.Console.WriteLine("SUB") Return z * z End Function, Y + 1) S = If(False, _ Sub(Z As Integer) System.Console.WriteLine("SUB") End Sub, Y + 1) System.Console.WriteLine(S) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 77 (0x4d) .maxstack 2 .locals init (Object V_0) //Y IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: stloc.0 IL_0007: ldsfld "C._Closure$__.$I0-0 As <generated method>" IL_000c: brfalse.s IL_0015 IL_000e: ldsfld "C._Closure$__.$I0-0 As <generated method>" IL_0013: br.s IL_002b IL_0015: ldsfld "C._Closure$__.$I As C._Closure$__" IL_001a: ldftn "Function C._Closure$__._Lambda$__0-0(Integer) As Integer" IL_0020: newobj "Sub VB$AnonymousDelegate_0(Of Integer, Integer)..ctor(Object, System.IntPtr)" IL_0025: dup IL_0026: stsfld "C._Closure$__.$I0-0 As <generated method>" IL_002b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0030: pop IL_0031: ldloc.0 IL_0032: ldc.i4.1 IL_0033: box "Integer" IL_0038: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object" IL_003d: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0042: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0047: call "Sub System.Console.WriteLine(Object)" IL_004c: ret } ]]>).Compilation End Sub ' Conditional on expression tree <Fact()> Public Sub ExpressionTree() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System Imports System.Linq.Expressions Module Program Sub Main(args As String()) Dim testExpr As Expression(Of Func(Of Boolean, Long, Integer, Long)) = Function(x, y, z) If(x, y, z) Dim testFunc = testExpr.Compile() Dim testResult = testFunc(False, CLng(3), 100) Console.WriteLine(testResult) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 100 ]]>).Compilation End Sub ' Conditional on expression tree <Fact()> Public Sub ExpressionTree_2() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer on Imports System Imports System.Linq.Expressions Module Program Sub Main(args As String()) Dim testExpr As Expression(Of Func(Of TestStruct, Long?, Integer, Integer?)) = Function(x, y, z) If(x, y, z) Dim testFunc = testExpr.Compile() Dim testResult1 = testFunc(New TestStruct(), Nothing, 10) Dim testResult2 = testFunc(New TestStruct(), 10, Nothing) Console.WriteLine (testResult1) Console.WriteLine (testResult2) End Sub End Module Public Structure TestStruct Public Shared Operator IsTrue(ts As TestStruct) As Boolean Return False End Operator Public Shared Operator IsFalse(ts As TestStruct) As Boolean Return True End Operator End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 10 0 ]]>).Compilation End Sub ' Multiple conditional operator in expression <Fact> Public Sub MultipleConditional() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim S = If(False, 1, If(True, 2, 3)) Console.Write(S) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 2 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 17 (0x11) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000b: call "Sub System.Console.Write(Object)" IL_0010: ret }]]>).Compilation End Sub ' Arguments are of types: bool, constant, enum <Fact> Public Sub EnumAsArguments() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim testResult = If(False, 0, color.Blue) Console.WriteLine(testResult) testResult = If(False, 5, color.Blue) Console.WriteLine(testResult) End Sub End Module Enum color Red Green Blue End Enum </file> </compilation>, expectedOutput:=<![CDATA[ 2 2 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000b: call "Sub System.Console.WriteLine(Object)" IL_0010: ldc.i4.2 IL_0011: box "Integer" IL_0016: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001b: call "Sub System.Console.WriteLine(Object)" IL_0020: ret }]]>).Compilation End Sub ' Implicit type conversion on conditional <Fact> Public Sub ImplicitConversionForConditional() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim valueFromDatabase As Object Dim result As Decimal valueFromDatabase = DBNull.Value result = CDec(If(valueFromDatabase IsNot DBNull.Value, valueFromDatabase, 0)) Console.WriteLine(result) result = (If(valueFromDatabase IsNot DBNull.Value, CDec(valueFromDatabase), CDec(0))) Console.WriteLine(result) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 0 0 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 60 (0x3c) .maxstack 2 .locals init (Object V_0) //valueFromDatabase IL_0000: ldsfld "System.DBNull.Value As System.DBNull" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldsfld "System.DBNull.Value As System.DBNull" IL_000c: bne.un.s IL_0016 IL_000e: ldc.i4.0 IL_000f: box "Integer" IL_0014: br.s IL_0017 IL_0016: ldloc.0 IL_0017: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToDecimal(Object) As Decimal" IL_001c: call "Sub System.Console.WriteLine(Decimal)" IL_0021: ldloc.0 IL_0022: ldsfld "System.DBNull.Value As System.DBNull" IL_0027: bne.un.s IL_0030 IL_0029: ldsfld "Decimal.Zero As Decimal" IL_002e: br.s IL_0036 IL_0030: ldloc.0 IL_0031: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToDecimal(Object) As Decimal" IL_0036: call "Sub System.Console.WriteLine(Decimal)" IL_003b: ret }]]>).Compilation End Sub ' Not boolean type as conditional-argument <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub NotBooleanAsConditionalArgument() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim x = 1 Dim s = If("", x, 2) 'invalid s = If("True", x, 2) 'valid s = If("1", x, 2) 'valid End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 36 (0x24) .maxstack 1 .locals init (Integer V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldstr "" IL_0007: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(String) As Boolean" IL_000c: pop IL_000d: ldstr "True" IL_0012: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(String) As Boolean" IL_0017: pop IL_0018: ldstr "1" IL_001d: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(String) As Boolean" IL_0022: pop IL_0023: ret }]]>).Compilation End Sub ' Not boolean type as conditional-argument <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub NotBooleanAsConditionalArgument_2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim x = 1 Dim s = If(color.Green, x, 2) Console.WriteLine(S) s = If(color.Red, x, 2) Console.WriteLine(s) End Sub End Module Public Enum color Red Blue Green End Enum </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 ]]>) End Sub <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact> Public Sub FunctionWithNoReturnType() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim x = 1 Dim s = If(fun1(), x, 2) End Sub Private Function fun1() End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 1 .locals init (Object V_0) //x IL_0000: ldc.i4.1 IL_0001: box "Integer" IL_0006: stloc.0 IL_0007: call "Function C.fun1() As Object" IL_000c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean" IL_0011: brtrue.s IL_001b IL_0013: ldc.i4.2 IL_0014: box "Integer" IL_0019: br.s IL_001c IL_001b: ldloc.0 IL_001c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0021: pop IL_0022: ret }]]>).Compilation End Sub ' Const as conditional- argument <WorkItem(541452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541452")> <Fact()> Public Sub ConstAsArgument() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Const con As Boolean = True Dim s1 = If(con, 1, 2) Console.Write(s1) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call "Sub System.Console.Write(Integer)" IL_0006: ret } ]]>).Compilation End Sub ' Const i As Integer = IF <Fact> Public Sub AssignIfToConst() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Const s As Integer = If(1>2, 9, 92) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Program.Main", <![CDATA[ { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }]]>).Compilation End Sub ' IF used in Redim <WorkItem(528563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528563")> <Fact> Public Sub IfUsedInRedim() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module Program Sub Main(args As String()) Dim s1 As Integer() ReDim Preserve s1(If(True, 10, 101)) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Program.Main", <![CDATA[ { // Code size 20 (0x14) .maxstack 2 .locals init (Integer() V_0) //s1 IL_0000: ldloc.0 IL_0001: ldc.i4.s 11 IL_0003: newarr "Integer" IL_0008: call "Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array" IL_000d: castclass "Integer()" IL_0012: stloc.0 IL_0013: ret }]]>).Compilation End Sub ' IF on attribute <Fact> Public Sub IFOnAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System &lt;Assembly: CLSCompliant(If(True, False, True))&gt; Public Class base Public Shared sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyDiagnostics() End Sub ' #const val =if <Fact> Public Sub PredefinedConst() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Public Class Program Public Shared Sub Main() #Const ifconst = If(True, 1, 2) #If ifconst = 1 Then #End If End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Program.Main", <![CDATA[ { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }]]>).Compilation End Sub ' IF as function name <Fact> Public Sub IFAsFunctionName() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Module M1 Sub Main() End Sub Public Function [if](ByVal arg As String) As String Return arg End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("M1.if", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }]]>).Compilation End Sub ' IF as Optional parameter <Fact()> Public Sub IFAsOptionalParameter() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Module M1 Sub Main() goo() End Sub Public Sub goo(Optional ByVal arg As String = If(False, "6", "61")) System.Console.WriteLine(arg) End Sub End Module </file> </compilation>, expectedOutput:="61").Compilation End Sub ' IF used in For step <Fact()> Public Sub IFUsedInForStep() CompileAndVerify( <compilation> <file name="a.vb"> Module M1 Sub Main() Dim s10 As Boolean = False For c As Integer = 1 To 10 Step If(s10, 1, 2) Next End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe) End Sub ' Passing IF as byref arg <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub IFAsByrefArg() CompileAndVerify( <compilation> <file name="a.vb"> Module M1 Sub Main() Dim X = "123" Dim Y = "456" Dim Z = If(1 > 2, goo(X), goo(Y)) End Sub Private Function goo(ByRef p1 As String) p1 = "HELLO" End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("M1.Main", <![CDATA[ { // Code size 26 (0x1a) .maxstack 1 .locals init (String V_0, //X String V_1) //Y IL_0000: ldstr "123" IL_0005: stloc.0 IL_0006: ldstr "456" IL_000b: stloc.1 IL_000c: ldloca.s V_1 IL_000e: call "Function M1.goo(ByRef String) As Object" IL_0013: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0018: pop IL_0019: ret }]]>) End Sub <WorkItem(541674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541674")> <Fact> Public Sub TypeConversionInRuntime() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections.Generic Public Class Test Private Shared Sub Main() Dim a As Integer() = New Integer() {} Dim b As New List(Of Integer)() Dim c As IEnumerable(Of Integer) = If(a.Length > 0, a, DirectCast(b, IEnumerable(Of Integer))) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseDll).VerifyIL("Test.Main", <![CDATA[ { // Code size 25 (0x19) .maxstack 2 .locals init (Integer() V_0, //a System.Collections.Generic.List(Of Integer) V_1) //b IL_0000: ldc.i4.0 IL_0001: newarr "Integer" IL_0006: stloc.0 IL_0007: newobj "Sub System.Collections.Generic.List(Of Integer)..ctor()" IL_000c: stloc.1 IL_000d: ldloc.0 IL_000e: ldlen IL_000f: conv.i4 IL_0010: ldc.i4.0 IL_0011: bgt.s IL_0016 IL_0013: ldloc.1 IL_0014: pop IL_0015: ret IL_0016: ldloc.0 IL_0017: pop IL_0018: ret } ]]>).Compilation End Sub <WorkItem(541673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541673")> <Fact> Public Sub TypeConversionInRuntime_1() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Public Interface IB Function f() As Integer End Interface Public Class AB1 Implements IB Public Function f() As Integer Implements IB.f Return 42 End Function End Class Public Class AB2 Implements IB Public Function f() As Integer Implements IB.f Return 1 End Function End Class Class MainClass Public Shared Sub g(p As Boolean) Dim x = (If(p, DirectCast(New AB1(), IB), DirectCast(New AB2(), IB))).f() End Sub Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("MainClass.g", <![CDATA[ { // Code size 29 (0x1d) .maxstack 1 .locals init (IB V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000a IL_0003: newobj "Sub AB2..ctor()" IL_0008: br.s IL_0011 IL_000a: newobj "Sub AB1..ctor()" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: callvirt "Function IB.f() As Integer" IL_0016: box "Integer" IL_001b: pop IL_001c: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInRuntime_2() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Public Interface IB Function f() As Integer End Interface Public Class AB1 Implements IB Public Function f() As Integer Implements IB.f Return 42 End Function End Class Class MainClass Public Shared Sub g(p As Boolean) Dim x = (If(p, DirectCast(New AB1(), IB), DirectCast(New AB1(), IB))).f() End Sub Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("MainClass.g", <![CDATA[ { // Code size 29 (0x1d) .maxstack 1 .locals init (IB V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000a IL_0003: newobj "Sub AB1..ctor()" IL_0008: br.s IL_0011 IL_000a: newobj "Sub AB1..ctor()" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: callvirt "Function IB.f() As Integer" IL_0016: box "Integer" IL_001b: pop IL_001c: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInRuntime_3() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Public Interface IB Function f() As Integer End Interface Public Class AB1 Implements IB Public Function f() As Integer Implements IB.f Return 42 End Function End Class Class MainClass Public Shared Sub g(p As Boolean) Dim x = (If(DirectCast(New AB1(), IB), DirectCast(New AB1(), IB))).f() End Sub Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("MainClass.g", <![CDATA[ { // Code size 28 (0x1c) .maxstack 2 .locals init (IB V_0) IL_0000: newobj "Sub AB1..ctor()" IL_0005: dup IL_0006: brtrue.s IL_0010 IL_0008: pop IL_0009: newobj "Sub AB1..ctor()" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: callvirt "Function IB.f() As Integer" IL_0015: box "Integer" IL_001a: pop IL_001b: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function m1() As IBase End Interface Class Derived Public Shared mask As Integer = 1 End Class Class Test1 Implements IBase Private y As IBase Private x As IBase Private cnt As Integer = 0 Public Sub New(link As IBase) x = Me y = link If y Is Nothing Then y = Me End If End Sub Public Shared Sub Main() End Sub Public Function m1() As IBase Implements IBase.m1 Return If(Derived.mask = 0, x, y) End Function 'version1 (explicit impl in original repro) Public Function m2() As IBase Return If(Derived.mask = 0, Me, y) End Function 'version2 End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.m1", <![CDATA[ { // Code size 21 (0x15) .maxstack 1 IL_0000: ldsfld "Derived.mask As Integer" IL_0005: brfalse.s IL_000e IL_0007: ldarg.0 IL_0008: ldfld "Test1.y As IBase" IL_000d: ret IL_000e: ldarg.0 IL_000f: ldfld "Test1.x As IBase" IL_0014: ret }]]>).VerifyIL("Test1.m2", <![CDATA[ { // Code size 16 (0x10) .maxstack 1 IL_0000: ldsfld "Derived.mask As Integer" IL_0005: brfalse.s IL_000e IL_0007: ldarg.0 IL_0008: ldfld "Test1.y As IBase" IL_000d: ret IL_000e: ldarg.0 IL_000f: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_1() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function m1() As IBase End Interface Class Derived Public Shared mask As Integer = 1 End Class Class Test1 Implements IBase Private y As IBase Private x As IBase Private cnt As Integer = 0 Public Sub New(link As IBase) x = Me y = link If y Is Nothing Then y = Me End If End Sub Public Shared Sub Main() End Sub Public Function m1() As IBase Implements IBase.m1 Return If(x, y) End Function 'version1 (explicit impl in original repro) Public Function m2() As IBase Return If(Me, y) End Function 'version2 End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.m1", <![CDATA[ { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "Test1.x As IBase" IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.0 IL_000b: ldfld "Test1.y As IBase" IL_0010: ret }]]>).VerifyIL("Test1.m2", <![CDATA[ { // Code size 12 (0xc) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_000b IL_0004: pop IL_0005: ldarg.0 IL_0006: ldfld "Test1.y As IBase" IL_000b: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_2() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function m1() As IBase End Interface Class Derived Public Shared mask As Integer = 1 End Class Class Test1 Implements IBase Private y As IBase Private x As IBase Private cnt As Integer = 0 Public Sub New(link As IBase) x = Me y = link If y Is Nothing Then y = Me End If End Sub Public Shared Sub Main() End Sub Public Function m1() As IBase Implements IBase.m1 Return If (x, DirectCast(y, IBase)) End Function 'version1 (explicit impl in original repro) Public Function m2() As IBase Return If (DirectCast(Me, IBase), y) End Function 'version2 End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.m1", <![CDATA[ { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "Test1.x As IBase" IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.0 IL_000b: ldfld "Test1.y As IBase" IL_0010: ret }]]>).VerifyIL("Test1.m2", <![CDATA[ { // Code size 12 (0xc) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_000b IL_0004: pop IL_0005: ldarg.0 IL_0006: ldfld "Test1.y As IBase" IL_000b: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_3() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections Imports System.Collections.Generic Class Test1 Implements IEnumerable Dim x As IEnumerator Dim y As IEnumerator Public Shared Sub Main() End Sub Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return If(Me IsNot Nothing, DirectCast(x, IEnumerator), DirectCast(y, IEnumerator)) End Function End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.GetEnumerator", <![CDATA[ { // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_000a IL_0003: ldarg.0 IL_0004: ldfld "Test1.y As System.Collections.IEnumerator" IL_0009: ret IL_000a: ldarg.0 IL_000b: ldfld "Test1.x As System.Collections.IEnumerator" IL_0010: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_4() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function GetEnumerator() As IBase End Interface Interface IDerived Inherits IBase End Interface Structure struct Implements IBase Public Shared Sub Main() End Sub Function GetEnumerator() As IBase Implements IBase.GetEnumerator Dim x As IDerived Dim y As IDerived Return If(x IsNot Nothing, DirectCast(x, IBase), DirectCast(y, IBase)) End Function End Structure </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("struct.GetEnumerator", <![CDATA[ { // Code size 9 (0x9) .maxstack 1 .locals init (IDerived V_0, //x IDerived V_1, //y IBase V_2) IL_0000: ldloc.0 IL_0001: brtrue.s IL_0005 IL_0003: ldloc.1 IL_0004: ret IL_0005: ldloc.0 IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: ret } ]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_5() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function GetEnumerator() As IBase End Interface Interface IDerived Inherits IBase End Interface Structure struct Implements IDerived Public Shared Sub Main() End Sub Function GetEnumerator() As IBase Implements IBase.GetEnumerator Dim x As IDerived Dim y As IDerived Return If(x IsNot Nothing, DirectCast(x, IDerived), DirectCast(y, IDerived)) End Function End Structure </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("struct.GetEnumerator", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 .locals init (IDerived V_0, //x IDerived V_1) //y IL_0000: ldloc.0 IL_0001: brtrue.s IL_0005 IL_0003: ldloc.1 IL_0004: ret IL_0005: ldloc.0 IL_0006: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_6() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Interface IBase Function GetEnumerator() As IBase End Interface Interface IDerived Inherits IBase End Interface Structure struct Implements IDerived Public Shared Sub Main() End Sub Function GetEnumerator() As IBase Implements IBase.GetEnumerator Dim x = GetInterface() Dim y = GetInterface() Dim z = If(x IsNot Nothing, DirectCast(x, IBase), DirectCast(y, IBase)) End Function Function GetInterface() As IBase Return Nothing End Function End Structure </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("struct.GetEnumerator", <![CDATA[ { // Code size 34 (0x22) .maxstack 1 .locals init (IBase V_0, //GetEnumerator Object V_1, //x Object V_2) //y IL_0000: ldarg.0 IL_0001: call "Function struct.GetInterface() As IBase" IL_0006: stloc.1 IL_0007: ldarg.0 IL_0008: call "Function struct.GetInterface() As IBase" IL_000d: stloc.2 IL_000e: ldloc.1 IL_000f: brtrue.s IL_0019 IL_0011: ldloc.2 IL_0012: castclass "IBase" IL_0017: br.s IL_001f IL_0019: ldloc.1 IL_001a: castclass "IBase" IL_001f: pop IL_0020: ldloc.0 IL_0021: ret }]]>).Compilation End Sub <Fact, WorkItem(545065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545065")> Public Sub IfOnConstrainedMethodTypeParameter() CompileAndVerify( <compilation> <file name="a.vb"> Friend Module BIFOpResult0011mod Public Sub scen7(Of T As Class)(ByVal arg As T) Dim s7_a As T = arg Dim s7_b As T = Nothing Dim s7_c = If(s7_a, s7_b) System.Console.Write(s7_c) End Sub Sub Main() scen7(Of String)("Q") End Sub End Module </file> </compilation>, expectedOutput:="Q").VerifyIL("BIFOpResult0011mod.scen7", <![CDATA[ { // Code size 30 (0x1e) .maxstack 2 .locals init (T V_0) //s7_b IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: initobj "T" IL_0009: dup IL_000a: box "T" IL_000f: brtrue.s IL_0013 IL_0011: pop IL_0012: ldloc.0 IL_0013: box "T" IL_0018: call "Sub System.Console.Write(Object)" IL_001d: ret }]]>) End Sub <Fact> Public Sub IfOnUnconstrainedMethodTypeParameter() CompileAndVerify( <compilation> <file name="a.vb"> Friend Module Mod1 Sub M1(Of T)(arg1 As T, arg2 As T) System.Console.WriteLine(If(arg1, arg2)) End Sub Sub M2(Of T1, T2 As T1)(arg1 as T1, arg2 As T2) System.Console.WriteLine(If(arg2, arg1)) End Sub Sub Main() M1(Nothing, 1000) M1(1, 1000) M1(Nothing, "String Parameter 1") M1("String Parameter 2", "Should not print") M1(Of Integer?)(Nothing, 4) M1(Of Integer?)(5, 1000) M2(1000, 6) M2(Of Object, Integer?)(7, Nothing) M2(Of Object, Integer?)(1000, 8) M2(Of Integer?, Integer?)(9, Nothing) M2(Of Integer?, Integer?)(1000, 10) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 0 1 String Parameter 1 String Parameter 2 4 5 6 7 8 9 10 ]]>).VerifyIL("Mod1.M1", <![CDATA[ { // Code size 22 (0x16) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: box "T" IL_0007: brtrue.s IL_000b IL_0009: pop IL_000a: ldarg.1 IL_000b: box "T" IL_0010: call "Sub System.Console.WriteLine(Object)" IL_0015: ret } ]]>).VerifyIL("Mod1.M2", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 IL_0000: ldarg.1 IL_0001: box "T2" IL_0006: brtrue.s IL_000b IL_0008: ldarg.0 IL_0009: br.s IL_0016 IL_000b: ldarg.1 IL_000c: box "T2" IL_0011: unbox.any "T1" IL_0016: box "T1" IL_001b: call "Sub System.Console.WriteLine(Object)" IL_0020: ret } ]]>) End Sub <Fact> Public Sub IfOnUnconstrainedTypeParameterWithNothingLHS() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Friend Module Mod1 Sub M1(Of T)(arg As T) Console.WriteLine(If(Nothing, arg)) End Sub Sub Main() ' Note that this behavior is different than C#'s behavior. This is consistent with Roslyn's handling ' of If(Nothing, 1), which will evaluate to 1 M1(1) Console.WriteLine(If(Nothing, 1)) M1("String Parameter 1") M1(Of Integer?)(3) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 1 1 String Parameter 1 3 ]]>).VerifyIL("Mod1.M1", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: box "T" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) End Sub <Fact> Public Sub IfOnUnconstrainedTypeParametersOldLanguageVersion() CreateCompilation( <compilation> <file name="a.vb"> Friend Module Mod1 Sub M1(Of T)(arg1 As T, arg2 As T) System.Console.WriteLine(If(arg1, arg2)) End Sub End Module </file> </compilation>, parseOptions:=TestOptions.Regular15_5).AssertTheseDiagnostics(<![CDATA[ BC36716: Visual Basic 15.5 does not support unconstrained type parameters in binary conditional expressions. System.Console.WriteLine(If(arg1, arg2)) ~~~~~~~~~~~~~~ ]]>) End Sub End Class End Namespace
-1
dotnet/roslyn
55,972
Add Import Directives to the VS options search text
Resolves https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1260748
JoeRobich
"2021-08-27T20:53:59Z"
"2021-08-31T18:50:41Z"
9ad67ca5b3931968c41bc88bddce4ffd696e807c
1f9bf9a09f12e4bcc3f1b4e1db861279e097eea5
Add Import Directives to the VS options search text. Resolves https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1260748
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.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="../CompilerExtensionsResources.resx"> <body> <trans-unit id="Absolute_path_expected"> <source>Absolute path expected.</source> <target state="translated">Ruta de acceso absoluta esperada.</target> <note /> </trans-unit> <trans-unit id="Abstract_Method"> <source>Abstract Method</source> <target state="translated">Método abstracto</target> <note>{locked: abstract}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note> </trans-unit> <trans-unit id="An_element_with_the_same_key_but_a_different_value_already_exists"> <source>An element with the same key but a different value already exists.</source> <target state="translated">Ya existe un elemento con la misma clave pero un valor distinto.</target> <note /> </trans-unit> <trans-unit id="Begins_with_I"> <source>Begins with I</source> <target state="translated">Empieza por I</target> <note>{locked:I}</note> </trans-unit> <trans-unit id="Class"> <source>Class</source> <target state="new">Class</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Delegate"> <source>Delegate</source> <target state="new">Delegate</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Enum"> <source>Enum</source> <target state="new">Enum</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Event"> <source>Event</source> <target state="new">Event</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Cast_is_redundant"> <source>Cast is redundant.</source> <target state="translated">La conversión es redundante.</target> <note /> </trans-unit> <trans-unit id="Expression_level_preferences"> <source>Expression-level preferences</source> <target state="translated">Preferencias de nivel de expresión</target> <note /> </trans-unit> <trans-unit id="Field_preferences"> <source>Field preferences</source> <target state="translated">Preferencias de campo</target> <note /> </trans-unit> <trans-unit id="Interface"> <source>Interface</source> <target state="new">Interface</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Language_keywords_vs_BCL_types_preferences"> <source>Language keywords vs BCL types preferences</source> <target state="translated">Preferencias de palabras clave frente a tipos de BCL</target> <note /> </trans-unit> <trans-unit id="Method"> <source>Method</source> <target state="translated">método</target> <note>{locked:method} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Missing_prefix_colon_0"> <source>Missing prefix: '{0}'</source> <target state="translated">Falta el prefijo: '{0}'</target> <note /> </trans-unit> <trans-unit id="Missing_suffix_colon_0"> <source>Missing suffix: '{0}'</source> <target state="translated">Falta el sufijo: '{0}'</target> <note /> </trans-unit> <trans-unit id="Modifier_preferences"> <source>Modifier preferences</source> <target state="translated">Preferencias de modificador</target> <note /> </trans-unit> <trans-unit id="Naming_rules"> <source>Naming rules</source> <target state="translated">Reglas de nomenclatura</target> <note /> </trans-unit> <trans-unit id="Naming_styles"> <source>Naming styles</source> <target state="translated">Estilos de nomenclatura</target> <note /> </trans-unit> <trans-unit id="New_line_preferences"> <source>New line preferences</source> <target state="translated">Nuevas preferencias de línea</target> <note /> </trans-unit> <trans-unit id="Non_Field_Members"> <source>Non-Field Members</source> <target state="translated">Miembros que no son un campo</target> <note>{locked:field}</note> </trans-unit> <trans-unit id="Organize_usings"> <source>Organize usings</source> <target state="translated">Organizar instrucciones Using</target> <note /> </trans-unit> <trans-unit id="Parameter_preferences"> <source>Parameter preferences</source> <target state="translated">Preferencias de parámetro</target> <note /> </trans-unit> <trans-unit id="Parentheses_preferences"> <source>Parentheses preferences</source> <target state="translated">Preferencias de paréntesis</target> <note /> </trans-unit> <trans-unit id="Pascal_Case"> <source>Pascal Case</source> <target state="translated">Pascal Case</target> <note /> </trans-unit> <trans-unit id="Prefix_0_does_not_match_expected_prefix_1"> <source>Prefix '{0}' does not match expected prefix '{1}'</source> <target state="translated">El prefijo "{0}" no coincide con el prefijo esperado "{1}".</target> <note /> </trans-unit> <trans-unit id="Prefix_0_is_not_expected"> <source>Prefix '{0}' is not expected</source> <target state="translated">No se espera el prefijo "{0}"</target> <note /> </trans-unit> <trans-unit id="Private_Method"> <source>Private Method</source> <target state="translated">Método privado</target> <note>{locked: private}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note> </trans-unit> <trans-unit id="Private_or_Internal_Field"> <source>Private or Internal Field</source> <target state="translated">Campo privado o interno</target> <note>{locked: private}{locked: internal}{locked:field}</note> </trans-unit> <trans-unit id="Private_or_Internal_Static_Field"> <source>Private or Internal Static Field</source> <target state="translated">Campo estático privado o interno</target> <note>{locked: private}{locked: internal}{locked:static}{locked:field}</note> </trans-unit> <trans-unit id="Property"> <source>Property</source> <target state="new">Property</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Public_or_Protected_Field"> <source>Public or Protected Field</source> <target state="translated">Campo público o protegido</target> <note>{locked: public}{locked: protected}{locked:field}</note> </trans-unit> <trans-unit id="Segment_size_must_be_power_of_2_greater_than_1"> <source>Segment size must be power of 2 greater than 1</source> <target state="translated">El tamaño del segmento debe ser una potencia de 2 mayor que 1</target> <note /> </trans-unit> <trans-unit id="Specified_sequence_has_duplicate_items"> <source>Specified sequence has duplicate items</source> <target state="translated">La secuencia especificada tiene elementos duplicados.</target> <note /> </trans-unit> <trans-unit id="Static_Field"> <source>Static Field</source> <target state="translated">Campo estático</target> <note>{locked:static}{locked:field} (unless the capitalization should be handled differently)</note> </trans-unit> <trans-unit id="Static_Method"> <source>Static Method</source> <target state="translated">Método estático</target> <note>{locked: static}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note> </trans-unit> <trans-unit id="Struct"> <source>Struct</source> <target state="new">Struct</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Suppression_preferences"> <source>Suppression preferences</source> <target state="translated">Preferencias de eliminación</target> <note /> </trans-unit> <trans-unit id="Symbol_specifications"> <source>Symbol specifications</source> <target state="translated">Especificaciones de símbolos</target> <note /> </trans-unit> <trans-unit id="The_first_word_0_must_begin_with_a_lower_case_character"> <source>The first word, '{0}', must begin with a lower case character</source> <target state="translated">La primera palabra, '{0}', debe comenzar con un carácter en minúscula</target> <note /> </trans-unit> <trans-unit id="The_first_word_0_must_begin_with_an_upper_case_character"> <source>The first word, '{0}', must begin with an upper case character</source> <target state="translated">La primera palabra, '{0}', debe comenzar con un carácter en mayúscula</target> <note /> </trans-unit> <trans-unit id="These_non_leading_words_must_begin_with_a_lowercase_letter_colon_0"> <source>These non-leading words must begin with a lowercase letter: {0}</source> <target state="translated">Las palabras que no están al principio deben comenzar con una letra minúscula: {0}</target> <note /> </trans-unit> <trans-unit id="These_non_leading_words_must_begin_with_an_upper_case_letter_colon_0"> <source>These non-leading words must begin with an upper case letter: {0}</source> <target state="translated">Las palabras que no están al principio deben comenzar con una letra mayúscula: {0}</target> <note /> </trans-unit> <trans-unit id="These_words_cannot_contain_lower_case_characters_colon_0"> <source>These words cannot contain lower case characters: {0}</source> <target state="translated">Estas palabras no pueden contener caracteres en minúscula: {0}</target> <note /> </trans-unit> <trans-unit id="These_words_cannot_contain_upper_case_characters_colon_0"> <source>These words cannot contain upper case characters: {0}</source> <target state="translated">Estas palabras no pueden contener caracteres en mayúscula: {0}</target> <note /> </trans-unit> <trans-unit id="These_words_must_begin_with_upper_case_characters_colon_0"> <source>These words must begin with upper case characters: {0}</source> <target state="translated">Estas palabras deben comenzar por caracteres en mayúscula: {0}</target> <note /> </trans-unit> <trans-unit id="Types"> <source>Types</source> <target state="translated">Tipos</target> <note>{locked:types} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="this_dot_and_Me_dot_preferences"> <source>this. and Me. preferences</source> <target state="translated">Preferencias de this. y .me</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="../CompilerExtensionsResources.resx"> <body> <trans-unit id="Absolute_path_expected"> <source>Absolute path expected.</source> <target state="translated">Ruta de acceso absoluta esperada.</target> <note /> </trans-unit> <trans-unit id="Abstract_Method"> <source>Abstract Method</source> <target state="translated">Método abstracto</target> <note>{locked: abstract}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note> </trans-unit> <trans-unit id="An_element_with_the_same_key_but_a_different_value_already_exists"> <source>An element with the same key but a different value already exists.</source> <target state="translated">Ya existe un elemento con la misma clave pero un valor distinto.</target> <note /> </trans-unit> <trans-unit id="Begins_with_I"> <source>Begins with I</source> <target state="translated">Empieza por I</target> <note>{locked:I}</note> </trans-unit> <trans-unit id="Class"> <source>Class</source> <target state="new">Class</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Delegate"> <source>Delegate</source> <target state="new">Delegate</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Enum"> <source>Enum</source> <target state="new">Enum</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Event"> <source>Event</source> <target state="new">Event</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Cast_is_redundant"> <source>Cast is redundant.</source> <target state="translated">La conversión es redundante.</target> <note /> </trans-unit> <trans-unit id="Expression_level_preferences"> <source>Expression-level preferences</source> <target state="translated">Preferencias de nivel de expresión</target> <note /> </trans-unit> <trans-unit id="Field_preferences"> <source>Field preferences</source> <target state="translated">Preferencias de campo</target> <note /> </trans-unit> <trans-unit id="Interface"> <source>Interface</source> <target state="new">Interface</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Language_keywords_vs_BCL_types_preferences"> <source>Language keywords vs BCL types preferences</source> <target state="translated">Preferencias de palabras clave frente a tipos de BCL</target> <note /> </trans-unit> <trans-unit id="Method"> <source>Method</source> <target state="translated">método</target> <note>{locked:method} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Missing_prefix_colon_0"> <source>Missing prefix: '{0}'</source> <target state="translated">Falta el prefijo: '{0}'</target> <note /> </trans-unit> <trans-unit id="Missing_suffix_colon_0"> <source>Missing suffix: '{0}'</source> <target state="translated">Falta el sufijo: '{0}'</target> <note /> </trans-unit> <trans-unit id="Modifier_preferences"> <source>Modifier preferences</source> <target state="translated">Preferencias de modificador</target> <note /> </trans-unit> <trans-unit id="Naming_rules"> <source>Naming rules</source> <target state="translated">Reglas de nomenclatura</target> <note /> </trans-unit> <trans-unit id="Naming_styles"> <source>Naming styles</source> <target state="translated">Estilos de nomenclatura</target> <note /> </trans-unit> <trans-unit id="New_line_preferences"> <source>New line preferences</source> <target state="translated">Nuevas preferencias de línea</target> <note /> </trans-unit> <trans-unit id="Non_Field_Members"> <source>Non-Field Members</source> <target state="translated">Miembros que no son un campo</target> <note>{locked:field}</note> </trans-unit> <trans-unit id="Organize_usings"> <source>Organize usings</source> <target state="translated">Organizar instrucciones Using</target> <note /> </trans-unit> <trans-unit id="Parameter_preferences"> <source>Parameter preferences</source> <target state="translated">Preferencias de parámetro</target> <note /> </trans-unit> <trans-unit id="Parentheses_preferences"> <source>Parentheses preferences</source> <target state="translated">Preferencias de paréntesis</target> <note /> </trans-unit> <trans-unit id="Pascal_Case"> <source>Pascal Case</source> <target state="translated">Pascal Case</target> <note /> </trans-unit> <trans-unit id="Prefix_0_does_not_match_expected_prefix_1"> <source>Prefix '{0}' does not match expected prefix '{1}'</source> <target state="translated">El prefijo "{0}" no coincide con el prefijo esperado "{1}".</target> <note /> </trans-unit> <trans-unit id="Prefix_0_is_not_expected"> <source>Prefix '{0}' is not expected</source> <target state="translated">No se espera el prefijo "{0}"</target> <note /> </trans-unit> <trans-unit id="Private_Method"> <source>Private Method</source> <target state="translated">Método privado</target> <note>{locked: private}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note> </trans-unit> <trans-unit id="Private_or_Internal_Field"> <source>Private or Internal Field</source> <target state="translated">Campo privado o interno</target> <note>{locked: private}{locked: internal}{locked:field}</note> </trans-unit> <trans-unit id="Private_or_Internal_Static_Field"> <source>Private or Internal Static Field</source> <target state="translated">Campo estático privado o interno</target> <note>{locked: private}{locked: internal}{locked:static}{locked:field}</note> </trans-unit> <trans-unit id="Property"> <source>Property</source> <target state="new">Property</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Public_or_Protected_Field"> <source>Public or Protected Field</source> <target state="translated">Campo público o protegido</target> <note>{locked: public}{locked: protected}{locked:field}</note> </trans-unit> <trans-unit id="Segment_size_must_be_power_of_2_greater_than_1"> <source>Segment size must be power of 2 greater than 1</source> <target state="translated">El tamaño del segmento debe ser una potencia de 2 mayor que 1</target> <note /> </trans-unit> <trans-unit id="Specified_sequence_has_duplicate_items"> <source>Specified sequence has duplicate items</source> <target state="translated">La secuencia especificada tiene elementos duplicados.</target> <note /> </trans-unit> <trans-unit id="Static_Field"> <source>Static Field</source> <target state="translated">Campo estático</target> <note>{locked:static}{locked:field} (unless the capitalization should be handled differently)</note> </trans-unit> <trans-unit id="Static_Method"> <source>Static Method</source> <target state="translated">Método estático</target> <note>{locked: static}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note> </trans-unit> <trans-unit id="Struct"> <source>Struct</source> <target state="new">Struct</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Suppression_preferences"> <source>Suppression preferences</source> <target state="translated">Preferencias de eliminación</target> <note /> </trans-unit> <trans-unit id="Symbol_specifications"> <source>Symbol specifications</source> <target state="translated">Especificaciones de símbolos</target> <note /> </trans-unit> <trans-unit id="The_first_word_0_must_begin_with_a_lower_case_character"> <source>The first word, '{0}', must begin with a lower case character</source> <target state="translated">La primera palabra, '{0}', debe comenzar con un carácter en minúscula</target> <note /> </trans-unit> <trans-unit id="The_first_word_0_must_begin_with_an_upper_case_character"> <source>The first word, '{0}', must begin with an upper case character</source> <target state="translated">La primera palabra, '{0}', debe comenzar con un carácter en mayúscula</target> <note /> </trans-unit> <trans-unit id="These_non_leading_words_must_begin_with_a_lowercase_letter_colon_0"> <source>These non-leading words must begin with a lowercase letter: {0}</source> <target state="translated">Las palabras que no están al principio deben comenzar con una letra minúscula: {0}</target> <note /> </trans-unit> <trans-unit id="These_non_leading_words_must_begin_with_an_upper_case_letter_colon_0"> <source>These non-leading words must begin with an upper case letter: {0}</source> <target state="translated">Las palabras que no están al principio deben comenzar con una letra mayúscula: {0}</target> <note /> </trans-unit> <trans-unit id="These_words_cannot_contain_lower_case_characters_colon_0"> <source>These words cannot contain lower case characters: {0}</source> <target state="translated">Estas palabras no pueden contener caracteres en minúscula: {0}</target> <note /> </trans-unit> <trans-unit id="These_words_cannot_contain_upper_case_characters_colon_0"> <source>These words cannot contain upper case characters: {0}</source> <target state="translated">Estas palabras no pueden contener caracteres en mayúscula: {0}</target> <note /> </trans-unit> <trans-unit id="These_words_must_begin_with_upper_case_characters_colon_0"> <source>These words must begin with upper case characters: {0}</source> <target state="translated">Estas palabras deben comenzar por caracteres en mayúscula: {0}</target> <note /> </trans-unit> <trans-unit id="Types"> <source>Types</source> <target state="translated">Tipos</target> <note>{locked:types} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="this_dot_and_Me_dot_preferences"> <source>this. and Me. preferences</source> <target state="translated">Preferencias de this. y .me</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,972
Add Import Directives to the VS options search text
Resolves https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1260748
JoeRobich
"2021-08-27T20:53:59Z"
"2021-08-31T18:50:41Z"
9ad67ca5b3931968c41bc88bddce4ffd696e807c
1f9bf9a09f12e4bcc3f1b4e1db861279e097eea5
Add Import Directives to the VS options search text. Resolves https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1260748
./src/EditorFeatures/CSharpTest2/Recommendations/PropertyKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 PropertyKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeInsideClass() { await VerifyKeywordAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterAttributeInsideClass() { await VerifyKeywordAsync( @"class C { [Goo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterProperty() { await VerifyKeywordAsync( @"class C { int Goo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterField() { await VerifyKeywordAsync( @"class C { int Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterEvent() { await VerifyKeywordAsync( @"class C { event Action<int> Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttribute() { await VerifyAbsenceAsync( @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameterAttribute() { await VerifyAbsenceAsync( @"class C { void Goo([$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAttribute1() { await VerifyAbsenceAsync( @"class C { int Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAttribute2() { await VerifyAbsenceAsync( @"class C { int Goo { get { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEventAttribute1() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEventAttribute2() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo { add { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInterface() { await VerifyKeywordAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInStruct() { await VerifyKeywordAsync( @"struct S { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnum() { await VerifyAbsenceAsync( @"enum E { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(51756, "https://github.com/dotnet/roslyn/issues/51756")] public async Task TestInRecordPositionalParameter1() { await VerifyKeywordAsync("public record R([$$] string M);"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(51756, "https://github.com/dotnet/roslyn/issues/51756")] public async Task TestInRecordPositionalParameter2() { await VerifyKeywordAsync("public record R([$$ SomeAttribute] string M);"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(51756, "https://github.com/dotnet/roslyn/issues/51756")] public async Task TestInRecordPositionalParameter3() { await VerifyKeywordAsync("public record R([$$ string M);"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(51756, "https://github.com/dotnet/roslyn/issues/51756")] public async Task TestInRecordPositionalParameter4() { await VerifyKeywordAsync("public record R([$$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 PropertyKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeInsideClass() { await VerifyKeywordAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterAttributeInsideClass() { await VerifyKeywordAsync( @"class C { [Goo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterProperty() { await VerifyKeywordAsync( @"class C { int Goo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterField() { await VerifyKeywordAsync( @"class C { int Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterEvent() { await VerifyKeywordAsync( @"class C { event Action<int> Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttribute() { await VerifyAbsenceAsync( @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameterAttribute() { await VerifyAbsenceAsync( @"class C { void Goo([$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAttribute1() { await VerifyAbsenceAsync( @"class C { int Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAttribute2() { await VerifyAbsenceAsync( @"class C { int Goo { get { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEventAttribute1() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEventAttribute2() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo { add { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInterface() { await VerifyKeywordAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInStruct() { await VerifyKeywordAsync( @"struct S { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnum() { await VerifyAbsenceAsync( @"enum E { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(51756, "https://github.com/dotnet/roslyn/issues/51756")] public async Task TestInRecordPositionalParameter1() { await VerifyKeywordAsync("public record R([$$] string M);"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(51756, "https://github.com/dotnet/roslyn/issues/51756")] public async Task TestInRecordPositionalParameter2() { await VerifyKeywordAsync("public record R([$$ SomeAttribute] string M);"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(51756, "https://github.com/dotnet/roslyn/issues/51756")] public async Task TestInRecordPositionalParameter3() { await VerifyKeywordAsync("public record R([$$ string M);"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(51756, "https://github.com/dotnet/roslyn/issues/51756")] public async Task TestInRecordPositionalParameter4() { await VerifyKeywordAsync("public record R([$$"); } } }
-1
dotnet/roslyn
55,972
Add Import Directives to the VS options search text
Resolves https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1260748
JoeRobich
"2021-08-27T20:53:59Z"
"2021-08-31T18:50:41Z"
9ad67ca5b3931968c41bc88bddce4ffd696e807c
1f9bf9a09f12e4bcc3f1b4e1db861279e097eea5
Add Import Directives to the VS options search text. Resolves https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1260748
./src/VisualStudio/Core/Test/Venus/DocumentService_IntegrationTests.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.ComponentModel.Composition Imports System.Threading Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Media Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.CSharp.Syntax Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.FindUsages Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.LanguageServices.CodeLens Imports Microsoft.VisualStudio.LanguageServices.FindUsages Imports Microsoft.VisualStudio.OLE.Interop Imports Microsoft.VisualStudio.Shell Imports Microsoft.VisualStudio.Shell.FindAllReferences Imports Microsoft.VisualStudio.Shell.TableControl Imports Microsoft.VisualStudio.Shell.TableManager Imports Microsoft.VisualStudio.Text Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus <UseExportProvider> Public Class DocumentService_IntegrationTests Private Shared ReadOnly s_compositionWithMockDiagnosticUpdateSourceRegistrationService As TestComposition = EditorTestCompositions.EditorFeatures _ .AddExcludedPartTypes(GetType(IDiagnosticUpdateSourceRegistrationService)) _ .AddParts(GetType(MockDiagnosticUpdateSourceRegistrationService)) <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestFindUsageIntegration() As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class {|Original:C|} { [|C|]$$ c; } </Document> <Document FilePath="Mapped.cs"> class {|Definition:C1|} { [|C1|] c; }reference </Document> </Project> </Workspace> ' TODO: Use VisualStudioTestComposition or move the feature down to EditorFeatures and avoid dependency on IServiceProvider. ' https://github.com/dotnet/roslyn/issues/46279 Dim composition = EditorTestCompositions.EditorFeatures.AddParts(GetType(MockServiceProvider)) Using workspace = TestWorkspace.Create(input, composition:=composition, documentServiceProvider:=TestDocumentServiceProvider.Instance) Dim presenter = New StreamingFindUsagesPresenter(workspace, workspace.ExportProvider.AsExportProvider()) Dim tuple = presenter.StartSearch("test", supportsReferences:=True) Dim context = tuple.context Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim cursorPosition = cursorDocument.CursorPosition.Value Dim startDocument = workspace.CurrentSolution.GetDocument(cursorDocument.Id) Assert.NotNull(startDocument) Dim findRefsService = startDocument.GetLanguageService(Of IFindUsagesService) Await findRefsService.FindReferencesAsync(startDocument, cursorPosition, context, CancellationToken.None) Dim definitionDocument = workspace.Documents.First(Function(d) d.AnnotatedSpans.ContainsKey("Definition")) Dim definitionText = Await workspace.CurrentSolution.GetDocument(definitionDocument.Id).GetTextAsync() Dim definitionSpan = definitionDocument.AnnotatedSpans("Definition").Single() Dim referenceSpan = definitionDocument.SelectedSpans.First() Dim expected = { (definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(definitionSpan).Start, definitionText.Lines.GetLineFromPosition(definitionSpan.Start).ToString().Trim()), (definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString().Trim())} Dim factory = TestFindAllReferencesService.Instance.LastWindow.MyTableManager.LastSink.LastFactory Dim snapshot = factory.GetCurrentSnapshot() Dim actual = New List(Of (String, LinePosition, String)) For i = 0 To snapshot.Count - 1 Dim name As Object = Nothing Dim line As Object = Nothing Dim position As Object = Nothing Dim content As Object = Nothing Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.DocumentName, name)) Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.Line, line)) Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.Column, position)) Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.Text, content)) actual.Add((DirectCast(name, String), New LinePosition(CType(line, Integer), CType(position, Integer)), DirectCast(content, String))) Next ' confirm that all FAR results are mapped to ones in mapped.cs file rather than ones in original.cs AssertEx.SetEqual(expected, actual) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCodeLensIntegration() As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class {|Original:C|} { [|C|] c { get; }; } </Document> <Document FilePath="Mapped.cs"> class {|Definition:C1|} { [|C1|] c { get; }; }reference </Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(input, documentServiceProvider:=TestDocumentServiceProvider.Instance) Dim codelensService = New RemoteCodeLensReferencesService() Dim originalDocument = workspace.Documents.First(Function(d) d.AnnotatedSpans.ContainsKey("Original")) Dim startDocument = workspace.CurrentSolution.GetDocument(originalDocument.Id) Assert.NotNull(startDocument) Dim root = Await startDocument.GetSyntaxRootAsync() Dim node = root.FindNode(originalDocument.AnnotatedSpans("Original").First()).AncestorsAndSelf().OfType(Of ClassDeclarationSyntax).First() Dim results = Await codelensService.FindReferenceLocationsAsync(workspace.CurrentSolution, startDocument.Id, node, CancellationToken.None) Assert.True(results.HasValue) Dim definitionDocument = workspace.Documents.First(Function(d) d.AnnotatedSpans.ContainsKey("Definition")) Dim definitionText = Await workspace.CurrentSolution.GetDocument(definitionDocument.Id).GetTextAsync() Dim referenceSpan = definitionDocument.SelectedSpans.First() Dim expected = {(definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString())} Dim actual = New List(Of (String, LinePosition, String)) For Each result In results.Value actual.Add((result.FilePath, New LinePosition(result.LineNumber, result.ColumnNumber), result.ReferenceLineText)) Next ' confirm that all FAR results are mapped to ones in mapped.cs file rather than ones in original.cs AssertEx.SetEqual(expected, actual) End Using End Function <InlineData(True)> <InlineData(False)> <WpfTheory, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestDocumentOperationCanApplyChange(ignoreUnchangeableDocuments As Boolean) As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class C { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(input, documentServiceProvider:=TestDocumentServiceProvider.Instance, ignoreUnchangeableDocumentsWhenApplyingChanges:=ignoreUnchangeableDocuments) Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) ' made a change Dim newDocument = document.WithText(SourceText.From("")) ' confirm the change Assert.Equal(String.Empty, (Await newDocument.GetTextAsync()).ToString()) ' confirm apply changes are not supported Assert.False(document.CanApplyChange()) Assert.Equal(ignoreUnchangeableDocuments, workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges) ' see whether changes can be applied to the solution If ignoreUnchangeableDocuments Then Assert.True(workspace.TryApplyChanges(newDocument.Project.Solution)) ' Changes should not be made if Workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges is true Dim currentDocument = workspace.CurrentSolution.GetDocument(document.Id) Assert.True(currentDocument.GetTextSynchronously(CancellationToken.None).ContentEquals(document.GetTextSynchronously(CancellationToken.None))) Else ' should throw if Workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges is false Assert.Throws(Of NotSupportedException)(Sub() workspace.TryApplyChanges(newDocument.Project.Solution)) End If End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestDocumentOperationCanApplySupportDiagnostics() As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(input, composition:=s_compositionWithMockDiagnosticUpdateSourceRegistrationService, documentServiceProvider:=TestDocumentServiceProvider.Instance) Dim analyzerReference = New TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()) workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences({analyzerReference})) Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) Dim model = Await document.GetSemanticModelAsync() ' confirm there are errors Assert.True(model.GetDiagnostics().Any()) Assert.IsType(Of MockDiagnosticUpdateSourceRegistrationService)(workspace.GetService(Of IDiagnosticUpdateSourceRegistrationService)()) Dim diagnosticService = Assert.IsType(Of DiagnosticAnalyzerService)(workspace.GetService(Of IDiagnosticAnalyzerService)()) ' confirm diagnostic support is off for the document Assert.False(document.SupportsDiagnostics()) ' register the workspace to the service diagnosticService.CreateIncrementalAnalyzer(workspace) ' confirm that IDE doesn't report the diagnostics Dim diagnostics = Await diagnosticService.GetDiagnosticsAsync(workspace.CurrentSolution, documentId:=document.Id) Assert.False(diagnostics.Any()) End Using End Function Private Class TestDocumentServiceProvider Implements IDocumentServiceProvider Public Shared ReadOnly Instance As TestDocumentServiceProvider = New TestDocumentServiceProvider() Public Function GetService(Of TService As {Class, IDocumentService})() As TService Implements IDocumentServiceProvider.GetService If TypeOf SpanMapper.Instance Is TService Then Return TryCast(SpanMapper.Instance, TService) ElseIf TypeOf Excerpter.Instance Is TService Then Return TryCast(Excerpter.Instance, TService) ElseIf TypeOf DocumentOperations.Instance Is TService Then Return TryCast(DocumentOperations.Instance, TService) End If Return Nothing End Function Private Class SpanMapper Implements ISpanMappingService Public Shared ReadOnly Instance As SpanMapper = New SpanMapper() Public ReadOnly Property SupportsMappingImportDirectives As Boolean = False Implements ISpanMappingService.SupportsMappingImportDirectives Public Async Function MapSpansAsync(document As Document, spans As IEnumerable(Of TextSpan), cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of MappedSpanResult)) Implements ISpanMappingService.MapSpansAsync Dim testWorkspace = DirectCast(document.Project.Solution.Workspace, TestWorkspace) Dim testDocument = testWorkspace.GetTestDocument(document.Id) Dim mappedTestDocument = testWorkspace.Documents.First(Function(d) d.Id <> testDocument.Id) Dim mappedDocument = testWorkspace.CurrentSolution.GetDocument(mappedTestDocument.Id) Dim mappedSource = Await mappedDocument.GetTextAsync(cancellationToken).ConfigureAwait(False) Dim results = New List(Of MappedSpanResult) For Each span In spans If testDocument.AnnotatedSpans("Original").First() = span Then Dim mappedSpan = mappedTestDocument.AnnotatedSpans("Definition").First() Dim lineSpan = mappedSource.Lines.GetLinePositionSpan(mappedSpan) results.Add(New MappedSpanResult(mappedDocument.FilePath, lineSpan, mappedSpan)) ElseIf testDocument.SelectedSpans.First() = span Then Dim mappedSpan = mappedTestDocument.SelectedSpans.First() Dim lineSpan = mappedSource.Lines.GetLinePositionSpan(mappedSpan) results.Add(New MappedSpanResult(mappedDocument.FilePath, lineSpan, mappedSpan)) Else Throw New Exception("shouldn't reach here") End If Next Return results.ToImmutableArray() End Function Public Function GetMappedTextChangesAsync(oldDocument As Document, newDocument As Document, cancellationToken As CancellationToken) _ As Task(Of ImmutableArray(Of (mappedFilePath As String, mappedTextChange As Microsoft.CodeAnalysis.Text.TextChange))) _ Implements ISpanMappingService.GetMappedTextChangesAsync Throw New NotImplementedException() End Function End Class Private Class Excerpter Implements IDocumentExcerptService Public Shared ReadOnly Instance As Excerpter = New Excerpter() Public Async Function TryExcerptAsync(document As Document, span As TextSpan, mode As ExcerptMode, cancellationToken As CancellationToken) As Task(Of ExcerptResult?) Implements IDocumentExcerptService.TryExcerptAsync Dim testWorkspace = DirectCast(document.Project.Solution.Workspace, TestWorkspace) Dim testDocument = testWorkspace.GetTestDocument(document.Id) Dim mappedTestDocument = testWorkspace.Documents.First(Function(d) d.Id <> testDocument.Id) Dim mappedDocument = testWorkspace.CurrentSolution.GetDocument(mappedTestDocument.Id) Dim mappedSource = Await mappedDocument.GetTextAsync(cancellationToken).ConfigureAwait(False) Dim mappedSpan As TextSpan If testDocument.AnnotatedSpans("Original").First() = span Then mappedSpan = mappedTestDocument.AnnotatedSpans("Definition").First() ElseIf testDocument.SelectedSpans.First() = span Then mappedSpan = mappedTestDocument.SelectedSpans.First() Else Throw New Exception("shouldn't reach here") End If Dim line = mappedSource.Lines.GetLineFromPosition(mappedSpan.Start) Return New ExcerptResult(mappedSource.GetSubText(line.Span), New TextSpan(mappedSpan.Start - line.Start, mappedSpan.Length), ImmutableArray.Create(New ClassifiedSpan(New TextSpan(0, line.Span.Length), ClassificationTypeNames.Text)), document, span) End Function End Class Private Class DocumentOperations Implements IDocumentOperationService Public Shared ReadOnly Instance As DocumentOperations = New DocumentOperations() Public ReadOnly Property CanApplyChange As Boolean Implements IDocumentOperationService.CanApplyChange Get Return False End Get End Property Public ReadOnly Property SupportDiagnostics As Boolean Implements IDocumentOperationService.SupportDiagnostics Get Return False End Get End Property End Class End Class <PartNotDiscoverable> <Export(GetType(SVsServiceProvider))> Private Class MockServiceProvider Implements SVsServiceProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function GetService(serviceType As Type) As Object Implements SVsServiceProvider.GetService If GetType(SVsFindAllReferences) = serviceType Then Return TestFindAllReferencesService.Instance End If Return Nothing End Function End Class Private Class TestFindAllReferencesService Implements IFindAllReferencesService Public Shared ReadOnly Instance As TestFindAllReferencesService = New TestFindAllReferencesService() ' this mock is not thread-safe. don't use it concurrently Public LastWindow As FindAllReferencesWindow Public Function StartSearch(label As String) As IFindAllReferencesWindow Implements IFindAllReferencesService.StartSearch LastWindow = New FindAllReferencesWindow(label) Return LastWindow End Function End Class Private Class FindAllReferencesWindow Implements IFindAllReferencesWindow Public ReadOnly Label As String Public ReadOnly MyTableControl As WpfTableControl = New WpfTableControl() Public ReadOnly MyTableManager As TableManager = New TableManager() Public Sub New(label As String) Me.Label = label End Sub Public ReadOnly Property TableControl As IWpfTableControl Implements IFindAllReferencesWindow.TableControl Get Return MyTableControl End Get End Property Public ReadOnly Property Manager As ITableManager Implements IFindAllReferencesWindow.Manager Get Return MyTableManager End Get End Property Public Property Title As String Implements IFindAllReferencesWindow.Title Public Event Closed As EventHandler Implements IFindAllReferencesWindow.Closed #Region "Not Implemented" Public Sub AddCommandTarget(target As IOleCommandTarget, ByRef [next] As IOleCommandTarget) Implements IFindAllReferencesWindow.AddCommandTarget Throw New NotImplementedException() End Sub #End Region Public Sub SetProgress(progress As Double) Implements IFindAllReferencesWindow.SetProgress End Sub Public Sub SetProgress(completed As Integer, maximum As Integer) Implements IFindAllReferencesWindow.SetProgress End Sub End Class Private Class TableDataSink Implements ITableDataSink ' not thread safe. it should never be used concurrently Public LastFactory As ITableEntriesSnapshotFactory Public Property IsStable As Boolean Implements ITableDataSink.IsStable Public Sub AddFactory(newFactory As ITableEntriesSnapshotFactory, Optional removeAllFactories As Boolean = False) Implements ITableDataSink.AddFactory LastFactory = newFactory End Sub Public Sub FactorySnapshotChanged(factory As ITableEntriesSnapshotFactory) Implements ITableDataSink.FactorySnapshotChanged LastFactory = factory End Sub #Region "Not Implemented" Public Sub AddEntries(newEntries As IReadOnlyList(Of ITableEntry), Optional removeAllEntries As Boolean = False) Implements ITableDataSink.AddEntries Throw New NotImplementedException() End Sub Public Sub RemoveEntries(oldEntries As IReadOnlyList(Of ITableEntry)) Implements ITableDataSink.RemoveEntries Throw New NotImplementedException() End Sub Public Sub ReplaceEntries(oldEntries As IReadOnlyList(Of ITableEntry), newEntries As IReadOnlyList(Of ITableEntry)) Implements ITableDataSink.ReplaceEntries Throw New NotImplementedException() End Sub Public Sub RemoveAllEntries() Implements ITableDataSink.RemoveAllEntries Throw New NotImplementedException() End Sub Public Sub AddSnapshot(newSnapshot As ITableEntriesSnapshot, Optional removeAllSnapshots As Boolean = False) Implements ITableDataSink.AddSnapshot Throw New NotImplementedException() End Sub Public Sub RemoveSnapshot(oldSnapshot As ITableEntriesSnapshot) Implements ITableDataSink.RemoveSnapshot Throw New NotImplementedException() End Sub Public Sub RemoveAllSnapshots() Implements ITableDataSink.RemoveAllSnapshots Throw New NotImplementedException() End Sub Public Sub ReplaceSnapshot(oldSnapshot As ITableEntriesSnapshot, newSnapshot As ITableEntriesSnapshot) Implements ITableDataSink.ReplaceSnapshot Throw New NotImplementedException() End Sub Public Sub RemoveFactory(oldFactory As ITableEntriesSnapshotFactory) Implements ITableDataSink.RemoveFactory Throw New NotImplementedException() End Sub Public Sub ReplaceFactory(oldFactory As ITableEntriesSnapshotFactory, newFactory As ITableEntriesSnapshotFactory) Implements ITableDataSink.ReplaceFactory Throw New NotImplementedException() End Sub Public Sub RemoveAllFactories() Implements ITableDataSink.RemoveAllFactories Throw New NotImplementedException() End Sub #End Region End Class Private Class TableManager Implements ITableManager Private ReadOnly _sources As List(Of ITableDataSource) = New List(Of ITableDataSource)() Public LastSink As TableDataSink Public ReadOnly Property Identifier As String Implements ITableManager.Identifier Get Return "Test" End Get End Property Public ReadOnly Property Sources As IReadOnlyList(Of ITableDataSource) Implements ITableManager.Sources Get Return _sources End Get End Property Public Event SourcesChanged As EventHandler Implements ITableManager.SourcesChanged Public Function AddSource(source As ITableDataSource, ParamArray columns() As String) As Boolean Implements ITableManager.AddSource Return AddSource(source, columns.ToImmutableArray()) End Function Public Function AddSource(source As ITableDataSource, columns As IReadOnlyCollection(Of String)) As Boolean Implements ITableManager.AddSource LastSink = New TableDataSink() source.Subscribe(LastSink) _sources.Add(source) Return True End Function Public Function RemoveSource(source As ITableDataSource) As Boolean Implements ITableManager.RemoveSource Return _sources.Remove(source) End Function #Region "Not Implemented" Public Function GetColumnsForSources(sources As IEnumerable(Of ITableDataSource)) As IReadOnlyList(Of String) Implements ITableManager.GetColumnsForSources Throw New NotImplementedException() End Function #End Region End Class Private Class WpfTableControl Implements IWpfTableControl2 Public Event GroupingsChanged As EventHandler Implements IWpfTableControl2.GroupingsChanged Private _states As List(Of ColumnState) = New List(Of ColumnState)({New ColumnState2(StandardTableColumnDefinitions2.Definition, isVisible:=True, width:=10)}) Public ReadOnly Property ColumnStates As IReadOnlyList(Of ColumnState) Implements IWpfTableControl.ColumnStates Get Return _states End Get End Property Public Sub SetColumnStates(states As IEnumerable(Of ColumnState)) Implements IWpfTableControl2.SetColumnStates _states = states.ToList() End Sub Public ReadOnly Property ColumnDefinitionManager As ITableColumnDefinitionManager Implements IWpfTableControl.ColumnDefinitionManager Get Return Nothing End Get End Property #Region "Not Implemented" Public ReadOnly Property IsDataStable As Boolean Implements IWpfTableControl2.IsDataStable Get Throw New NotImplementedException() End Get End Property Public Property NavigationBehavior As TableEntryNavigationBehavior Implements IWpfTableControl2.NavigationBehavior Get Throw New NotImplementedException() End Get Set(value As TableEntryNavigationBehavior) Throw New NotImplementedException() End Set End Property Public Property KeepSelectionInView As Boolean Implements IWpfTableControl2.KeepSelectionInView Get Throw New NotImplementedException() End Get Set(value As Boolean) Throw New NotImplementedException() End Set End Property Public Property ShowGroupingLine As Boolean Implements IWpfTableControl2.ShowGroupingLine Get Throw New NotImplementedException() End Get Set(value As Boolean) Throw New NotImplementedException() End Set End Property Public Property RaiseDataUnstableChangeDelay As TimeSpan Implements IWpfTableControl2.RaiseDataUnstableChangeDelay Get Throw New NotImplementedException() End Get Set(value As TimeSpan) Throw New NotImplementedException() End Set End Property Public Property SelectedItemActiveBackground As Brush Implements IWpfTableControl2.SelectedItemActiveBackground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public Property SelectedItemActiveForeground As Brush Implements IWpfTableControl2.SelectedItemActiveForeground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public Property SelectedItemInactiveBackground As Brush Implements IWpfTableControl2.SelectedItemInactiveBackground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public Property SelectedItemInactiveForeground As Brush Implements IWpfTableControl2.SelectedItemInactiveForeground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public ReadOnly Property Manager As ITableManager Implements IWpfTableControl.Manager Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property Control As FrameworkElement Implements IWpfTableControl.Control Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property AutoSubscribe As Boolean Implements IWpfTableControl.AutoSubscribe Get Throw New NotImplementedException() End Get End Property Public Property SortFunction As Comparison(Of ITableEntryHandle) Implements IWpfTableControl.SortFunction Get Throw New NotImplementedException() End Get Set(value As Comparison(Of ITableEntryHandle)) Throw New NotImplementedException() End Set End Property Public Property SelectionMode As SelectionMode Implements IWpfTableControl.SelectionMode Get Throw New NotImplementedException() End Get Set(value As SelectionMode) Throw New NotImplementedException() End Set End Property Public ReadOnly Property Entries As IEnumerable(Of ITableEntryHandle) Implements IWpfTableControl.Entries Get Throw New NotImplementedException() End Get End Property Public Property SelectedEntries As IEnumerable(Of ITableEntryHandle) Implements IWpfTableControl.SelectedEntries Get Throw New NotImplementedException() End Get Set(value As IEnumerable(Of ITableEntryHandle)) Throw New NotImplementedException() End Set End Property Public ReadOnly Property SelectedEntry As ITableEntryHandle Implements IWpfTableControl.SelectedEntry Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property SelectedOrFirstEntry As ITableEntryHandle Implements IWpfTableControl.SelectedOrFirstEntry Get Throw New NotImplementedException() End Get End Property Public Event DataStabilityChanged As EventHandler Implements IWpfTableControl2.DataStabilityChanged Public Event FiltersChanged As EventHandler(Of FiltersChangedEventArgs) Implements IWpfTableControl.FiltersChanged Public Event PreEntriesChanged As EventHandler Implements IWpfTableControl.PreEntriesChanged Public Event EntriesChanged As EventHandler(Of EntriesChangedEventArgs) Implements IWpfTableControl.EntriesChanged Public Sub SubscribeToDataSource(source As ITableDataSource) Implements IWpfTableControl.SubscribeToDataSource Throw New NotImplementedException() End Sub Public Sub SelectAll() Implements IWpfTableControl.SelectAll Throw New NotImplementedException() End Sub Public Sub UnselectAll() Implements IWpfTableControl.UnselectAll Throw New NotImplementedException() End Sub Public Sub RefreshUI() Implements IWpfTableControl.RefreshUI Throw New NotImplementedException() End Sub Public Function GetAllFilters() As IEnumerable(Of Tuple(Of String, IEntryFilter)) Implements IWpfTableControl2.GetAllFilters Throw New NotImplementedException() End Function Public Function UnsubscribeFromDataSource(source As ITableDataSource) As Boolean Implements IWpfTableControl.UnsubscribeFromDataSource Throw New NotImplementedException() End Function Public Function SetFilter(key As String, newFilter As IEntryFilter) As IEntryFilter Implements IWpfTableControl.SetFilter Throw New NotImplementedException() End Function Public Function GetFilter(key As String) As IEntryFilter Implements IWpfTableControl.GetFilter Throw New NotImplementedException() End Function Public Function ForceUpdateAsync() As Task(Of EntriesChangedEventArgs) Implements IWpfTableControl.ForceUpdateAsync Throw New NotImplementedException() End Function Public Sub Dispose() Implements IDisposable.Dispose End Sub #End Region 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.ComponentModel.Composition Imports System.Threading Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Media Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.CSharp.Syntax Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.FindUsages Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.LanguageServices.CodeLens Imports Microsoft.VisualStudio.LanguageServices.FindUsages Imports Microsoft.VisualStudio.OLE.Interop Imports Microsoft.VisualStudio.Shell Imports Microsoft.VisualStudio.Shell.FindAllReferences Imports Microsoft.VisualStudio.Shell.TableControl Imports Microsoft.VisualStudio.Shell.TableManager Imports Microsoft.VisualStudio.Text Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus <UseExportProvider> Public Class DocumentService_IntegrationTests Private Shared ReadOnly s_compositionWithMockDiagnosticUpdateSourceRegistrationService As TestComposition = EditorTestCompositions.EditorFeatures _ .AddExcludedPartTypes(GetType(IDiagnosticUpdateSourceRegistrationService)) _ .AddParts(GetType(MockDiagnosticUpdateSourceRegistrationService)) <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestFindUsageIntegration() As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class {|Original:C|} { [|C|]$$ c; } </Document> <Document FilePath="Mapped.cs"> class {|Definition:C1|} { [|C1|] c; }reference </Document> </Project> </Workspace> ' TODO: Use VisualStudioTestComposition or move the feature down to EditorFeatures and avoid dependency on IServiceProvider. ' https://github.com/dotnet/roslyn/issues/46279 Dim composition = EditorTestCompositions.EditorFeatures.AddParts(GetType(MockServiceProvider)) Using workspace = TestWorkspace.Create(input, composition:=composition, documentServiceProvider:=TestDocumentServiceProvider.Instance) Dim presenter = New StreamingFindUsagesPresenter(workspace, workspace.ExportProvider.AsExportProvider()) Dim tuple = presenter.StartSearch("test", supportsReferences:=True) Dim context = tuple.context Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim cursorPosition = cursorDocument.CursorPosition.Value Dim startDocument = workspace.CurrentSolution.GetDocument(cursorDocument.Id) Assert.NotNull(startDocument) Dim findRefsService = startDocument.GetLanguageService(Of IFindUsagesService) Await findRefsService.FindReferencesAsync(startDocument, cursorPosition, context, CancellationToken.None) Dim definitionDocument = workspace.Documents.First(Function(d) d.AnnotatedSpans.ContainsKey("Definition")) Dim definitionText = Await workspace.CurrentSolution.GetDocument(definitionDocument.Id).GetTextAsync() Dim definitionSpan = definitionDocument.AnnotatedSpans("Definition").Single() Dim referenceSpan = definitionDocument.SelectedSpans.First() Dim expected = { (definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(definitionSpan).Start, definitionText.Lines.GetLineFromPosition(definitionSpan.Start).ToString().Trim()), (definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString().Trim())} Dim factory = TestFindAllReferencesService.Instance.LastWindow.MyTableManager.LastSink.LastFactory Dim snapshot = factory.GetCurrentSnapshot() Dim actual = New List(Of (String, LinePosition, String)) For i = 0 To snapshot.Count - 1 Dim name As Object = Nothing Dim line As Object = Nothing Dim position As Object = Nothing Dim content As Object = Nothing Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.DocumentName, name)) Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.Line, line)) Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.Column, position)) Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.Text, content)) actual.Add((DirectCast(name, String), New LinePosition(CType(line, Integer), CType(position, Integer)), DirectCast(content, String))) Next ' confirm that all FAR results are mapped to ones in mapped.cs file rather than ones in original.cs AssertEx.SetEqual(expected, actual) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCodeLensIntegration() As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class {|Original:C|} { [|C|] c { get; }; } </Document> <Document FilePath="Mapped.cs"> class {|Definition:C1|} { [|C1|] c { get; }; }reference </Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(input, documentServiceProvider:=TestDocumentServiceProvider.Instance) Dim codelensService = New RemoteCodeLensReferencesService() Dim originalDocument = workspace.Documents.First(Function(d) d.AnnotatedSpans.ContainsKey("Original")) Dim startDocument = workspace.CurrentSolution.GetDocument(originalDocument.Id) Assert.NotNull(startDocument) Dim root = Await startDocument.GetSyntaxRootAsync() Dim node = root.FindNode(originalDocument.AnnotatedSpans("Original").First()).AncestorsAndSelf().OfType(Of ClassDeclarationSyntax).First() Dim results = Await codelensService.FindReferenceLocationsAsync(workspace.CurrentSolution, startDocument.Id, node, CancellationToken.None) Assert.True(results.HasValue) Dim definitionDocument = workspace.Documents.First(Function(d) d.AnnotatedSpans.ContainsKey("Definition")) Dim definitionText = Await workspace.CurrentSolution.GetDocument(definitionDocument.Id).GetTextAsync() Dim referenceSpan = definitionDocument.SelectedSpans.First() Dim expected = {(definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString())} Dim actual = New List(Of (String, LinePosition, String)) For Each result In results.Value actual.Add((result.FilePath, New LinePosition(result.LineNumber, result.ColumnNumber), result.ReferenceLineText)) Next ' confirm that all FAR results are mapped to ones in mapped.cs file rather than ones in original.cs AssertEx.SetEqual(expected, actual) End Using End Function <InlineData(True)> <InlineData(False)> <WpfTheory, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestDocumentOperationCanApplyChange(ignoreUnchangeableDocuments As Boolean) As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class C { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(input, documentServiceProvider:=TestDocumentServiceProvider.Instance, ignoreUnchangeableDocumentsWhenApplyingChanges:=ignoreUnchangeableDocuments) Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) ' made a change Dim newDocument = document.WithText(SourceText.From("")) ' confirm the change Assert.Equal(String.Empty, (Await newDocument.GetTextAsync()).ToString()) ' confirm apply changes are not supported Assert.False(document.CanApplyChange()) Assert.Equal(ignoreUnchangeableDocuments, workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges) ' see whether changes can be applied to the solution If ignoreUnchangeableDocuments Then Assert.True(workspace.TryApplyChanges(newDocument.Project.Solution)) ' Changes should not be made if Workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges is true Dim currentDocument = workspace.CurrentSolution.GetDocument(document.Id) Assert.True(currentDocument.GetTextSynchronously(CancellationToken.None).ContentEquals(document.GetTextSynchronously(CancellationToken.None))) Else ' should throw if Workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges is false Assert.Throws(Of NotSupportedException)(Sub() workspace.TryApplyChanges(newDocument.Project.Solution)) End If End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestDocumentOperationCanApplySupportDiagnostics() As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(input, composition:=s_compositionWithMockDiagnosticUpdateSourceRegistrationService, documentServiceProvider:=TestDocumentServiceProvider.Instance) Dim analyzerReference = New TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()) workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences({analyzerReference})) Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) Dim model = Await document.GetSemanticModelAsync() ' confirm there are errors Assert.True(model.GetDiagnostics().Any()) Assert.IsType(Of MockDiagnosticUpdateSourceRegistrationService)(workspace.GetService(Of IDiagnosticUpdateSourceRegistrationService)()) Dim diagnosticService = Assert.IsType(Of DiagnosticAnalyzerService)(workspace.GetService(Of IDiagnosticAnalyzerService)()) ' confirm diagnostic support is off for the document Assert.False(document.SupportsDiagnostics()) ' register the workspace to the service diagnosticService.CreateIncrementalAnalyzer(workspace) ' confirm that IDE doesn't report the diagnostics Dim diagnostics = Await diagnosticService.GetDiagnosticsAsync(workspace.CurrentSolution, documentId:=document.Id) Assert.False(diagnostics.Any()) End Using End Function Private Class TestDocumentServiceProvider Implements IDocumentServiceProvider Public Shared ReadOnly Instance As TestDocumentServiceProvider = New TestDocumentServiceProvider() Public Function GetService(Of TService As {Class, IDocumentService})() As TService Implements IDocumentServiceProvider.GetService If TypeOf SpanMapper.Instance Is TService Then Return TryCast(SpanMapper.Instance, TService) ElseIf TypeOf Excerpter.Instance Is TService Then Return TryCast(Excerpter.Instance, TService) ElseIf TypeOf DocumentOperations.Instance Is TService Then Return TryCast(DocumentOperations.Instance, TService) End If Return Nothing End Function Private Class SpanMapper Implements ISpanMappingService Public Shared ReadOnly Instance As SpanMapper = New SpanMapper() Public ReadOnly Property SupportsMappingImportDirectives As Boolean = False Implements ISpanMappingService.SupportsMappingImportDirectives Public Async Function MapSpansAsync(document As Document, spans As IEnumerable(Of TextSpan), cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of MappedSpanResult)) Implements ISpanMappingService.MapSpansAsync Dim testWorkspace = DirectCast(document.Project.Solution.Workspace, TestWorkspace) Dim testDocument = testWorkspace.GetTestDocument(document.Id) Dim mappedTestDocument = testWorkspace.Documents.First(Function(d) d.Id <> testDocument.Id) Dim mappedDocument = testWorkspace.CurrentSolution.GetDocument(mappedTestDocument.Id) Dim mappedSource = Await mappedDocument.GetTextAsync(cancellationToken).ConfigureAwait(False) Dim results = New List(Of MappedSpanResult) For Each span In spans If testDocument.AnnotatedSpans("Original").First() = span Then Dim mappedSpan = mappedTestDocument.AnnotatedSpans("Definition").First() Dim lineSpan = mappedSource.Lines.GetLinePositionSpan(mappedSpan) results.Add(New MappedSpanResult(mappedDocument.FilePath, lineSpan, mappedSpan)) ElseIf testDocument.SelectedSpans.First() = span Then Dim mappedSpan = mappedTestDocument.SelectedSpans.First() Dim lineSpan = mappedSource.Lines.GetLinePositionSpan(mappedSpan) results.Add(New MappedSpanResult(mappedDocument.FilePath, lineSpan, mappedSpan)) Else Throw New Exception("shouldn't reach here") End If Next Return results.ToImmutableArray() End Function Public Function GetMappedTextChangesAsync(oldDocument As Document, newDocument As Document, cancellationToken As CancellationToken) _ As Task(Of ImmutableArray(Of (mappedFilePath As String, mappedTextChange As Microsoft.CodeAnalysis.Text.TextChange))) _ Implements ISpanMappingService.GetMappedTextChangesAsync Throw New NotImplementedException() End Function End Class Private Class Excerpter Implements IDocumentExcerptService Public Shared ReadOnly Instance As Excerpter = New Excerpter() Public Async Function TryExcerptAsync(document As Document, span As TextSpan, mode As ExcerptMode, cancellationToken As CancellationToken) As Task(Of ExcerptResult?) Implements IDocumentExcerptService.TryExcerptAsync Dim testWorkspace = DirectCast(document.Project.Solution.Workspace, TestWorkspace) Dim testDocument = testWorkspace.GetTestDocument(document.Id) Dim mappedTestDocument = testWorkspace.Documents.First(Function(d) d.Id <> testDocument.Id) Dim mappedDocument = testWorkspace.CurrentSolution.GetDocument(mappedTestDocument.Id) Dim mappedSource = Await mappedDocument.GetTextAsync(cancellationToken).ConfigureAwait(False) Dim mappedSpan As TextSpan If testDocument.AnnotatedSpans("Original").First() = span Then mappedSpan = mappedTestDocument.AnnotatedSpans("Definition").First() ElseIf testDocument.SelectedSpans.First() = span Then mappedSpan = mappedTestDocument.SelectedSpans.First() Else Throw New Exception("shouldn't reach here") End If Dim line = mappedSource.Lines.GetLineFromPosition(mappedSpan.Start) Return New ExcerptResult(mappedSource.GetSubText(line.Span), New TextSpan(mappedSpan.Start - line.Start, mappedSpan.Length), ImmutableArray.Create(New ClassifiedSpan(New TextSpan(0, line.Span.Length), ClassificationTypeNames.Text)), document, span) End Function End Class Private Class DocumentOperations Implements IDocumentOperationService Public Shared ReadOnly Instance As DocumentOperations = New DocumentOperations() Public ReadOnly Property CanApplyChange As Boolean Implements IDocumentOperationService.CanApplyChange Get Return False End Get End Property Public ReadOnly Property SupportDiagnostics As Boolean Implements IDocumentOperationService.SupportDiagnostics Get Return False End Get End Property End Class End Class <PartNotDiscoverable> <Export(GetType(SVsServiceProvider))> Private Class MockServiceProvider Implements SVsServiceProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function GetService(serviceType As Type) As Object Implements SVsServiceProvider.GetService If GetType(SVsFindAllReferences) = serviceType Then Return TestFindAllReferencesService.Instance End If Return Nothing End Function End Class Private Class TestFindAllReferencesService Implements IFindAllReferencesService Public Shared ReadOnly Instance As TestFindAllReferencesService = New TestFindAllReferencesService() ' this mock is not thread-safe. don't use it concurrently Public LastWindow As FindAllReferencesWindow Public Function StartSearch(label As String) As IFindAllReferencesWindow Implements IFindAllReferencesService.StartSearch LastWindow = New FindAllReferencesWindow(label) Return LastWindow End Function End Class Private Class FindAllReferencesWindow Implements IFindAllReferencesWindow Public ReadOnly Label As String Public ReadOnly MyTableControl As WpfTableControl = New WpfTableControl() Public ReadOnly MyTableManager As TableManager = New TableManager() Public Sub New(label As String) Me.Label = label End Sub Public ReadOnly Property TableControl As IWpfTableControl Implements IFindAllReferencesWindow.TableControl Get Return MyTableControl End Get End Property Public ReadOnly Property Manager As ITableManager Implements IFindAllReferencesWindow.Manager Get Return MyTableManager End Get End Property Public Property Title As String Implements IFindAllReferencesWindow.Title Public Event Closed As EventHandler Implements IFindAllReferencesWindow.Closed #Region "Not Implemented" Public Sub AddCommandTarget(target As IOleCommandTarget, ByRef [next] As IOleCommandTarget) Implements IFindAllReferencesWindow.AddCommandTarget Throw New NotImplementedException() End Sub #End Region Public Sub SetProgress(progress As Double) Implements IFindAllReferencesWindow.SetProgress End Sub Public Sub SetProgress(completed As Integer, maximum As Integer) Implements IFindAllReferencesWindow.SetProgress End Sub End Class Private Class TableDataSink Implements ITableDataSink ' not thread safe. it should never be used concurrently Public LastFactory As ITableEntriesSnapshotFactory Public Property IsStable As Boolean Implements ITableDataSink.IsStable Public Sub AddFactory(newFactory As ITableEntriesSnapshotFactory, Optional removeAllFactories As Boolean = False) Implements ITableDataSink.AddFactory LastFactory = newFactory End Sub Public Sub FactorySnapshotChanged(factory As ITableEntriesSnapshotFactory) Implements ITableDataSink.FactorySnapshotChanged LastFactory = factory End Sub #Region "Not Implemented" Public Sub AddEntries(newEntries As IReadOnlyList(Of ITableEntry), Optional removeAllEntries As Boolean = False) Implements ITableDataSink.AddEntries Throw New NotImplementedException() End Sub Public Sub RemoveEntries(oldEntries As IReadOnlyList(Of ITableEntry)) Implements ITableDataSink.RemoveEntries Throw New NotImplementedException() End Sub Public Sub ReplaceEntries(oldEntries As IReadOnlyList(Of ITableEntry), newEntries As IReadOnlyList(Of ITableEntry)) Implements ITableDataSink.ReplaceEntries Throw New NotImplementedException() End Sub Public Sub RemoveAllEntries() Implements ITableDataSink.RemoveAllEntries Throw New NotImplementedException() End Sub Public Sub AddSnapshot(newSnapshot As ITableEntriesSnapshot, Optional removeAllSnapshots As Boolean = False) Implements ITableDataSink.AddSnapshot Throw New NotImplementedException() End Sub Public Sub RemoveSnapshot(oldSnapshot As ITableEntriesSnapshot) Implements ITableDataSink.RemoveSnapshot Throw New NotImplementedException() End Sub Public Sub RemoveAllSnapshots() Implements ITableDataSink.RemoveAllSnapshots Throw New NotImplementedException() End Sub Public Sub ReplaceSnapshot(oldSnapshot As ITableEntriesSnapshot, newSnapshot As ITableEntriesSnapshot) Implements ITableDataSink.ReplaceSnapshot Throw New NotImplementedException() End Sub Public Sub RemoveFactory(oldFactory As ITableEntriesSnapshotFactory) Implements ITableDataSink.RemoveFactory Throw New NotImplementedException() End Sub Public Sub ReplaceFactory(oldFactory As ITableEntriesSnapshotFactory, newFactory As ITableEntriesSnapshotFactory) Implements ITableDataSink.ReplaceFactory Throw New NotImplementedException() End Sub Public Sub RemoveAllFactories() Implements ITableDataSink.RemoveAllFactories Throw New NotImplementedException() End Sub #End Region End Class Private Class TableManager Implements ITableManager Private ReadOnly _sources As List(Of ITableDataSource) = New List(Of ITableDataSource)() Public LastSink As TableDataSink Public ReadOnly Property Identifier As String Implements ITableManager.Identifier Get Return "Test" End Get End Property Public ReadOnly Property Sources As IReadOnlyList(Of ITableDataSource) Implements ITableManager.Sources Get Return _sources End Get End Property Public Event SourcesChanged As EventHandler Implements ITableManager.SourcesChanged Public Function AddSource(source As ITableDataSource, ParamArray columns() As String) As Boolean Implements ITableManager.AddSource Return AddSource(source, columns.ToImmutableArray()) End Function Public Function AddSource(source As ITableDataSource, columns As IReadOnlyCollection(Of String)) As Boolean Implements ITableManager.AddSource LastSink = New TableDataSink() source.Subscribe(LastSink) _sources.Add(source) Return True End Function Public Function RemoveSource(source As ITableDataSource) As Boolean Implements ITableManager.RemoveSource Return _sources.Remove(source) End Function #Region "Not Implemented" Public Function GetColumnsForSources(sources As IEnumerable(Of ITableDataSource)) As IReadOnlyList(Of String) Implements ITableManager.GetColumnsForSources Throw New NotImplementedException() End Function #End Region End Class Private Class WpfTableControl Implements IWpfTableControl2 Public Event GroupingsChanged As EventHandler Implements IWpfTableControl2.GroupingsChanged Private _states As List(Of ColumnState) = New List(Of ColumnState)({New ColumnState2(StandardTableColumnDefinitions2.Definition, isVisible:=True, width:=10)}) Public ReadOnly Property ColumnStates As IReadOnlyList(Of ColumnState) Implements IWpfTableControl.ColumnStates Get Return _states End Get End Property Public Sub SetColumnStates(states As IEnumerable(Of ColumnState)) Implements IWpfTableControl2.SetColumnStates _states = states.ToList() End Sub Public ReadOnly Property ColumnDefinitionManager As ITableColumnDefinitionManager Implements IWpfTableControl.ColumnDefinitionManager Get Return Nothing End Get End Property #Region "Not Implemented" Public ReadOnly Property IsDataStable As Boolean Implements IWpfTableControl2.IsDataStable Get Throw New NotImplementedException() End Get End Property Public Property NavigationBehavior As TableEntryNavigationBehavior Implements IWpfTableControl2.NavigationBehavior Get Throw New NotImplementedException() End Get Set(value As TableEntryNavigationBehavior) Throw New NotImplementedException() End Set End Property Public Property KeepSelectionInView As Boolean Implements IWpfTableControl2.KeepSelectionInView Get Throw New NotImplementedException() End Get Set(value As Boolean) Throw New NotImplementedException() End Set End Property Public Property ShowGroupingLine As Boolean Implements IWpfTableControl2.ShowGroupingLine Get Throw New NotImplementedException() End Get Set(value As Boolean) Throw New NotImplementedException() End Set End Property Public Property RaiseDataUnstableChangeDelay As TimeSpan Implements IWpfTableControl2.RaiseDataUnstableChangeDelay Get Throw New NotImplementedException() End Get Set(value As TimeSpan) Throw New NotImplementedException() End Set End Property Public Property SelectedItemActiveBackground As Brush Implements IWpfTableControl2.SelectedItemActiveBackground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public Property SelectedItemActiveForeground As Brush Implements IWpfTableControl2.SelectedItemActiveForeground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public Property SelectedItemInactiveBackground As Brush Implements IWpfTableControl2.SelectedItemInactiveBackground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public Property SelectedItemInactiveForeground As Brush Implements IWpfTableControl2.SelectedItemInactiveForeground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public ReadOnly Property Manager As ITableManager Implements IWpfTableControl.Manager Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property Control As FrameworkElement Implements IWpfTableControl.Control Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property AutoSubscribe As Boolean Implements IWpfTableControl.AutoSubscribe Get Throw New NotImplementedException() End Get End Property Public Property SortFunction As Comparison(Of ITableEntryHandle) Implements IWpfTableControl.SortFunction Get Throw New NotImplementedException() End Get Set(value As Comparison(Of ITableEntryHandle)) Throw New NotImplementedException() End Set End Property Public Property SelectionMode As SelectionMode Implements IWpfTableControl.SelectionMode Get Throw New NotImplementedException() End Get Set(value As SelectionMode) Throw New NotImplementedException() End Set End Property Public ReadOnly Property Entries As IEnumerable(Of ITableEntryHandle) Implements IWpfTableControl.Entries Get Throw New NotImplementedException() End Get End Property Public Property SelectedEntries As IEnumerable(Of ITableEntryHandle) Implements IWpfTableControl.SelectedEntries Get Throw New NotImplementedException() End Get Set(value As IEnumerable(Of ITableEntryHandle)) Throw New NotImplementedException() End Set End Property Public ReadOnly Property SelectedEntry As ITableEntryHandle Implements IWpfTableControl.SelectedEntry Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property SelectedOrFirstEntry As ITableEntryHandle Implements IWpfTableControl.SelectedOrFirstEntry Get Throw New NotImplementedException() End Get End Property Public Event DataStabilityChanged As EventHandler Implements IWpfTableControl2.DataStabilityChanged Public Event FiltersChanged As EventHandler(Of FiltersChangedEventArgs) Implements IWpfTableControl.FiltersChanged Public Event PreEntriesChanged As EventHandler Implements IWpfTableControl.PreEntriesChanged Public Event EntriesChanged As EventHandler(Of EntriesChangedEventArgs) Implements IWpfTableControl.EntriesChanged Public Sub SubscribeToDataSource(source As ITableDataSource) Implements IWpfTableControl.SubscribeToDataSource Throw New NotImplementedException() End Sub Public Sub SelectAll() Implements IWpfTableControl.SelectAll Throw New NotImplementedException() End Sub Public Sub UnselectAll() Implements IWpfTableControl.UnselectAll Throw New NotImplementedException() End Sub Public Sub RefreshUI() Implements IWpfTableControl.RefreshUI Throw New NotImplementedException() End Sub Public Function GetAllFilters() As IEnumerable(Of Tuple(Of String, IEntryFilter)) Implements IWpfTableControl2.GetAllFilters Throw New NotImplementedException() End Function Public Function UnsubscribeFromDataSource(source As ITableDataSource) As Boolean Implements IWpfTableControl.UnsubscribeFromDataSource Throw New NotImplementedException() End Function Public Function SetFilter(key As String, newFilter As IEntryFilter) As IEntryFilter Implements IWpfTableControl.SetFilter Throw New NotImplementedException() End Function Public Function GetFilter(key As String) As IEntryFilter Implements IWpfTableControl.GetFilter Throw New NotImplementedException() End Function Public Function ForceUpdateAsync() As Task(Of EntriesChangedEventArgs) Implements IWpfTableControl.ForceUpdateAsync Throw New NotImplementedException() End Function Public Sub Dispose() Implements IDisposable.Dispose End Sub #End Region End Class End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/CommonControls/MemberSelection.xaml
<UserControl x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls.MemberSelection" x:ClassModifier="internal" x:Name="MemberSelectionControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:utilities="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Utilities" xmlns:commoncontrols="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <UserControl.Resources> <Thickness x:Key="ButtonControlsPadding">2, 4, 4, 2</Thickness> <utilities:BooleanReverseConverter x:Key="BooleanReverseConverter"/> </UserControl.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <DataGrid x:Uid="MemberSelectionGrid" x:Name="MemberSelectionGrid" Grid.Column="0" Margin="0, 5, 12, 2" SelectionMode="Extended" AutoGenerateColumns="False" HeadersVisibility="Column" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" CanUserResizeColumns="False" CanUserResizeRows="False" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False" CanUserSortColumns="False" GridLinesVisibility="None" ScrollViewer.VerticalScrollBarVisibility="Auto" CanUserReorderColumns="False" Focusable="True" MinWidth="334" Height="Auto" Background="White" AutomationProperties.Name="{Binding SelectMemberListViewAutomationText}" ItemsSource="{Binding Members, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True, Mode=TwoWay}"> <DataGrid.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="BorderThickness" Value="0"/> <Setter Property="Focusable" Value="False"/> <Setter Property="AutomationProperties.Name" Value="{Binding SymbolName}" /> </Style> </DataGrid.CellStyle> <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Setter Property="AutomationProperties.Name" Value="{Binding RowSelectionAutomationText}"/> </Style> </DataGrid.RowStyle> <DataGrid.Columns> <DataGridTemplateColumn Width="Auto"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox AutomationProperties.Name="{Binding SymbolAutomationText}" AutomationProperties.AutomationId="{Binding SymbolName}" IsChecked="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" Width="Auto" IsEnabled="{Binding IsCheckable, UpdateSourceTrigger=PropertyChanged}" Focusable="True" ToolTipService.ShowOnDisabled="True" ToolTipService.IsEnabled="{Binding IsCheckable, Converter={StaticResource BooleanReverseConverter}, UpdateSourceTrigger=PropertyChanged}" ToolTipService.ToolTip="{Binding HelpText}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Width="*"> <DataGridTemplateColumn.Header> <TextBlock Text="{Binding ElementName=MemberSelectionControl, Path=MembersHeader}"/> </DataGridTemplateColumn.Header> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" MinWidth="186" Width="Auto" Margin="5, 2, 0, 2"> <Image x:Name="GlyphOfMember" Margin="8, 0, 5, 0" Source="{Binding Glyph}"/> <TextBlock x:Name="MemberName" Text="{Binding SymbolName}" Margin="0, 0, 5, 0" ToolTip="{Binding Accessibility}"/> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Width="100"> <DataGridTemplateColumn.Header> <TextBlock Text="{Binding ElementName=MemberSelectionControl, Path=MakeAbstractHeader}"/> </DataGridTemplateColumn.Header> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" Visibility="{Binding MakeAbstractVisibility}" IsEnabled="{Binding IsMakeAbstractCheckable, UpdateSourceTrigger=PropertyChanged}" AutomationProperties.Name="{Binding MakeAbstractCheckBoxAutomationText}" Focusable="True" Margin="0, 2, 0, 2" IsChecked="{Binding MakeAbstract, UpdateSourceTrigger=PropertyChanged}"> </CheckBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> <StackPanel Grid.Column="1" Orientation="Vertical" VerticalAlignment="Top" HorizontalAlignment="Center" Margin="0, 5, 0, 0" Width="Auto"> <Button x:Name="SelectAllButton" x:Uid="SelectAllButton" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Content="{Binding ElementName=MemberSelectionControl, Path=SelectAll}" Click="SelectAllButton_Click" Margin="2, 0, 0, 7" Width="Auto" Height="Auto" /> <Button x:Name="DeselectAllButton" x:Uid="DeselectAllButton" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Content="{Binding ElementName=MemberSelectionControl, Path=DeselectAll}" Click="DeselectAllButton_Click" Margin="2, 2, 0, 7" Width="Auto" Height="Auto" /> <Button x:Name="SelecDependentsButton" x:Uid="SelecDependentsButton" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Content="{Binding ElementName=MemberSelectionControl, Path=SelectDependents}" Click="SelectDependentsButton_Click" Margin="2, 2, 0, 7" Width="Auto" Height="Auto"/> <Button x:Name="SelectPublicButton" x:Uid="SelectPublicButton" Content="{Binding ElementName=MemberSelectionControl, Path=SelectPublic}" Margin="2, 0, 0, 0" Click="SelectPublic_Click" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Width="Auto" Height="Auto"/> </StackPanel> </Grid> </UserControl>
<UserControl x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls.MemberSelection" x:ClassModifier="internal" x:Name="MemberSelectionControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:utilities="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Utilities" xmlns:commoncontrols="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls" mc:Ignorable="d" xmlns:vsui="clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Shell.15.0" xmlns:vsshell="clr-namespace:Microsoft.VisualStudio.Shell;assembly=Microsoft.VisualStudio.Shell.15.0" d:DesignHeight="450" d:DesignWidth="800"> <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="../VSThemeDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> <Thickness x:Key="ButtonControlsPadding">2, 4, 4, 2</Thickness> <utilities:BooleanReverseConverter x:Key="BooleanReverseConverter"/> <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /> </ResourceDictionary> </UserControl.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <DataGrid x:Uid="MemberSelectionGrid" x:Name="MemberSelectionGrid" Grid.Column="0" Margin="0, 5, 12, 2" SelectionMode="Extended" AutoGenerateColumns="False" HeadersVisibility="Column" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" CanUserResizeColumns="False" CanUserResizeRows="False" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False" CanUserSortColumns="False" GridLinesVisibility="None" ScrollViewer.VerticalScrollBarVisibility="Auto" CanUserReorderColumns="False" Focusable="True" MinWidth="334" Height="Auto" AutomationProperties.Name="{Binding SelectMemberListViewAutomationText}" ItemsSource="{Binding Members, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True, Mode=TwoWay}"> <DataGrid.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="BorderThickness" Value="0"/> <Setter Property="Focusable" Value="False"/> <Setter Property="AutomationProperties.Name" Value="{Binding SymbolName}" /> </Style> </DataGrid.CellStyle> <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Setter Property="AutomationProperties.Name" Value="{Binding RowSelectionAutomationText}"/> </Style> </DataGrid.RowStyle> <DataGrid.Columns> <DataGridTemplateColumn Width="Auto"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Grid Background="{DynamicResource {x:Static vsui:HeaderColors.DefaultBrushKey}}"> <CheckBox AutomationProperties.Name="{Binding SymbolAutomationText}" AutomationProperties.AutomationId="{Binding SymbolName}" IsChecked="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" Width="Auto" IsEnabled="{Binding IsCheckable, UpdateSourceTrigger=PropertyChanged}" Focusable="True" ToolTipService.ShowOnDisabled="True" ToolTipService.IsEnabled="{Binding IsCheckable, Converter={StaticResource BooleanReverseConverter}, UpdateSourceTrigger=PropertyChanged}" ToolTipService.ToolTip="{Binding HelpText}"/> </Grid> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Width="*"> <DataGridTemplateColumn.Header> <TextBlock Text="{Binding ElementName=MemberSelectionControl, Path=MembersHeader}" Background="{DynamicResource {x:Static vsui:HeaderColors.DefaultBrushKey}}" /> </DataGridTemplateColumn.Header> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Grid Background="{DynamicResource {x:Static vsui:HeaderColors.DefaultBrushKey}}"> <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" MinWidth="186" Width="Auto" Margin="5, 2, 0, 2"> <Image x:Name="GlyphOfMember" Margin="8, 0, 5, 0" Source="{Binding Glyph}"/> <TextBlock x:Name="MemberName" Text="{Binding SymbolName}" Margin="0, 0, 5, 0" ToolTip="{Binding Accessibility}" Foreground="{DynamicResource {x:Static vsshell:VsBrushes.ToolWindowTextKey}}"/> </StackPanel> </Grid> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Width="100" x:Name="AbstractColumn"> <DataGridTemplateColumn.Header> <TextBlock Text="{Binding ElementName=MemberSelectionControl, Path=MakeAbstractHeader}" Background="{DynamicResource {x:Static vsui:HeaderColors.DefaultBrushKey}}" /> </DataGridTemplateColumn.Header> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Grid Background="{DynamicResource {x:Static vsui:HeaderColors.DefaultBrushKey}}"> <CheckBox HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" Visibility="{Binding MakeAbstractVisibility}" IsEnabled="{Binding IsMakeAbstractCheckable, UpdateSourceTrigger=PropertyChanged}" AutomationProperties.Name="{Binding MakeAbstractCheckBoxAutomationText}" Focusable="True" Margin="0, 2, 0, 2" IsChecked="{Binding MakeAbstract, UpdateSourceTrigger=PropertyChanged}"> </CheckBox> </Grid> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> <StackPanel Grid.Column="1" Orientation="Vertical" VerticalAlignment="Top" HorizontalAlignment="Center" Margin="0, 5, 0, 0" Width="Auto"> <Button x:Name="SelectAllButton" x:Uid="SelectAllButton" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Content="{Binding ElementName=MemberSelectionControl, Path=SelectAll}" Click="SelectAllButton_Click" Margin="2, 0, 0, 7" Width="Auto" Height="Auto" /> <Button x:Name="DeselectAllButton" x:Uid="DeselectAllButton" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Content="{Binding ElementName=MemberSelectionControl, Path=DeselectAll}" Click="DeselectAllButton_Click" Margin="2, 2, 0, 7" Width="Auto" Height="Auto" /> <Button x:Name="SelecDependentsButton" x:Uid="SelecDependentsButton" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Content="{Binding ElementName=MemberSelectionControl, Path=SelectDependents}" Visibility="{Binding ShowCheckDependentsButton, Converter={StaticResource BooleanToVisibilityConverter}}" Click="SelectDependentsButton_Click" Margin="2, 2, 0, 7" Width="Auto" Height="Auto"/> <Button x:Name="SelectPublicButton" x:Uid="SelectPublicButton" Content="{Binding ElementName=MemberSelectionControl, Path=SelectPublic}" Visibility="{Binding ShowPublicButton, Converter={StaticResource BooleanToVisibilityConverter}}" Margin="2, 0, 0, 0" Click="SelectPublic_Click" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Width="Auto" Height="Auto"/> </StackPanel> </Grid> </UserControl>
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/CommonControls/MemberSelection.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Windows; using System.Windows.Controls; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls { /// <summary> /// Interaction logic for MemberSelection.xaml /// </summary> internal partial class MemberSelection : UserControl { public string SelectDependents => ServicesVSResources.Select_Dependents; public string SelectPublic => ServicesVSResources.Select_Public; public string MembersHeader => ServicesVSResources.Members; public string MakeAbstractHeader => ServicesVSResources.Make_abstract; public string SelectAll => ServicesVSResources.Select_All; public string DeselectAll => ServicesVSResources.Deselect_All; public MemberSelectionViewModel ViewModel { get; } public MemberSelection(MemberSelectionViewModel viewModel) { ViewModel = viewModel; DataContext = ViewModel; InitializeComponent(); } private void SelectDependentsButton_Click(object sender, RoutedEventArgs e) => ViewModel.SelectDependents(); private void SelectPublic_Click(object sender, RoutedEventArgs e) => ViewModel.SelectPublic(); private void SelectAllButton_Click(object sender, RoutedEventArgs e) => ViewModel.SelectAll(); private void DeselectAllButton_Click(object sender, RoutedEventArgs e) => ViewModel.DeselectAll(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Windows; using System.Windows.Controls; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls { /// <summary> /// Interaction logic for MemberSelection.xaml /// </summary> internal partial class MemberSelection : UserControl { public string SelectDependents => ServicesVSResources.Select_Dependents; public string SelectPublic => ServicesVSResources.Select_Public; public string MembersHeader => ServicesVSResources.Members; public string MakeAbstractHeader => ServicesVSResources.Make_abstract; public string SelectAll => ServicesVSResources.Select_All; public string DeselectAll => ServicesVSResources.Deselect_All; public MemberSelectionViewModel ViewModel { get; } public MemberSelection(MemberSelectionViewModel viewModel) { ViewModel = viewModel; DataContext = ViewModel; ViewModel.PropertyChanged += ViewModel_PropertyChanged; InitializeComponent(); UpdateAbstractColumnVisibility(); } private void ViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == nameof(MemberSelectionViewModel.ShowMakeAbstract)) { UpdateAbstractColumnVisibility(); } } private void UpdateAbstractColumnVisibility() { AbstractColumn.Visibility = ViewModel.ShowMakeAbstract ? Visibility.Visible : Visibility.Collapsed; } private void SelectDependentsButton_Click(object sender, RoutedEventArgs e) => ViewModel.SelectDependents(); private void SelectPublic_Click(object sender, RoutedEventArgs e) => ViewModel.SelectPublic(); private void SelectAllButton_Click(object sender, RoutedEventArgs e) => ViewModel.SelectAll(); private void DeselectAllButton_Click(object sender, RoutedEventArgs e) => ViewModel.DeselectAll(); } }
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/CommonControls/MemberSelectionViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls { internal class MemberSelectionViewModel : AbstractNotifyPropertyChanged { private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> _symbolToDependentsMap; private readonly ImmutableDictionary<ISymbol, PullMemberUpSymbolViewModel> _symbolToMemberViewMap; public MemberSelectionViewModel( IUIThreadOperationExecutor uiThreadOperationExecutor, ImmutableArray<PullMemberUpSymbolViewModel> members, ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> dependentsMap, TypeKind destinationTypeKind = TypeKind.Class) { _uiThreadOperationExecutor = uiThreadOperationExecutor; // Use public property to hook property change events up Members = members; _symbolToDependentsMap = dependentsMap; _symbolToMemberViewMap = members.ToImmutableDictionary(memberViewModel => memberViewModel.Symbol); UpdateMembersBasedOnDestinationKind(destinationTypeKind); } public ImmutableArray<PullMemberUpSymbolViewModel> CheckedMembers => Members.WhereAsArray(m => m.IsChecked && m.IsCheckable); private ImmutableArray<PullMemberUpSymbolViewModel> _members; public ImmutableArray<PullMemberUpSymbolViewModel> Members { get => _members; set { var oldMembers = _members; if (SetProperty(ref _members, value)) { // If we have registered for events before, remove the handlers // to be a good citizen in the world if (!oldMembers.IsDefaultOrEmpty) { foreach (var oldMember in oldMembers) { oldMember.PropertyChanged -= MemberPropertyChangedHandler; } } foreach (var member in _members) { member.PropertyChanged += MemberPropertyChangedHandler; } } } } private void MemberPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(PullMemberUpSymbolViewModel.IsChecked)) { // Hook the CheckedMembers property change to each individual member checked status change NotifyPropertyChanged(nameof(CheckedMembers)); } } public void SelectPublic() => SelectMembers(Members.WhereAsArray(v => v.Symbol.DeclaredAccessibility == Accessibility.Public)); public void SelectAll() => SelectMembers(Members); internal void DeselectAll() => SelectMembers(Members, isChecked: false); public void SelectDependents() { var checkedMembers = Members .WhereAsArray(member => member.IsChecked && member.IsCheckable); var result = _uiThreadOperationExecutor.Execute( title: ServicesVSResources.Pull_Members_Up, defaultDescription: ServicesVSResources.Calculating_dependents, allowCancellation: true, showProgress: true, context => { foreach (var member in Members) { _symbolToDependentsMap[member.Symbol].Wait(context.UserCancellationToken); } }); if (result == UIThreadOperationStatus.Completed) { foreach (var member in checkedMembers) { var membersToSelected = FindDependentsRecursively(member.Symbol).SelectAsArray(symbol => _symbolToMemberViewMap[symbol]); SelectMembers(membersToSelected); } } } public ImmutableArray<(ISymbol member, bool makeAbstract)> GetSelectedMembers() => Members. Where(memberSymbolView => memberSymbolView.IsChecked && memberSymbolView.IsCheckable). SelectAsArray(memberViewModel => (member: memberViewModel.Symbol, makeAbstract: memberViewModel.IsMakeAbstractCheckable && memberViewModel.MakeAbstract)); public void UpdateMembersBasedOnDestinationKind(TypeKind destinationType) { var fields = Members.WhereAsArray(memberViewModel => memberViewModel.Symbol.IsKind(SymbolKind.Field)); var makeAbstractEnabledCheckboxes = Members. WhereAsArray(memberViewModel => !memberViewModel.Symbol.IsKind(SymbolKind.Field) && !memberViewModel.Symbol.IsAbstract); var isInterface = destinationType == TypeKind.Interface; // Disable field check box and make abstract if destination is interface foreach (var member in fields) { member.IsCheckable = !isInterface; member.TooltipText = isInterface ? ServicesVSResources.Interface_cannot_have_field : string.Empty; } foreach (var member in makeAbstractEnabledCheckboxes) { member.IsMakeAbstractCheckable = !isInterface; } } private static void SelectMembers(ImmutableArray<PullMemberUpSymbolViewModel> members, bool isChecked = true) { foreach (var member in members.Where(viewModel => viewModel.IsCheckable)) { member.IsChecked = isChecked; } } private ImmutableHashSet<ISymbol> FindDependentsRecursively(ISymbol member) { var queue = new Queue<ISymbol>(); // Under situation like two methods call each other, this hashset is used to // prevent the infinity loop. var visited = new HashSet<ISymbol>(); var result = new HashSet<ISymbol>(); queue.Enqueue(member); visited.Add(member); while (!queue.IsEmpty()) { var currentMember = queue.Dequeue(); result.Add(currentMember); visited.Add(currentMember); foreach (var dependent in _symbolToDependentsMap[currentMember].Result) { if (!visited.Contains(dependent)) { queue.Enqueue(dependent); } } } return result.ToImmutableHashSet(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls { internal class MemberSelectionViewModel : AbstractNotifyPropertyChanged { private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> _symbolToDependentsMap; private readonly ImmutableDictionary<ISymbol, MemberSymbolViewModel> _symbolToMemberViewMap; public MemberSelectionViewModel( IUIThreadOperationExecutor uiThreadOperationExecutor, ImmutableArray<MemberSymbolViewModel> members, ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> dependentsMap, TypeKind destinationTypeKind = TypeKind.Class, bool showDependentsButton = true, bool showPublicButton = true) { _uiThreadOperationExecutor = uiThreadOperationExecutor; // Use public property to hook property change events up Members = members.OrderBy(s => s.SymbolName).ToImmutableArray(); _symbolToDependentsMap = dependentsMap; _symbolToMemberViewMap = members.ToImmutableDictionary(memberViewModel => memberViewModel.Symbol); UpdateMembersBasedOnDestinationKind(destinationTypeKind); ShowCheckDependentsButton = showDependentsButton; ShowPublicButton = showPublicButton; } public bool ShowCheckDependentsButton { get; } public bool ShowPublicButton { get; } public bool ShowMakeAbstract => _members.Any(m => m.IsMakeAbstractCheckable); public ImmutableArray<MemberSymbolViewModel> CheckedMembers => Members.WhereAsArray(m => m.IsChecked && m.IsCheckable); private ImmutableArray<MemberSymbolViewModel> _members; public ImmutableArray<MemberSymbolViewModel> Members { get => _members; set { var oldMembers = _members; if (SetProperty(ref _members, value)) { // If we have registered for events before, remove the handlers // to be a good citizen in the world if (!oldMembers.IsDefaultOrEmpty) { foreach (var oldMember in oldMembers) { oldMember.PropertyChanged -= MemberPropertyChangedHandler; } } foreach (var member in _members) { member.PropertyChanged += MemberPropertyChangedHandler; } NotifyPropertyChanged(nameof(ShowMakeAbstract)); } } } private void MemberPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(MemberSymbolViewModel.IsChecked)) { // Hook the CheckedMembers property change to each individual member checked status change NotifyPropertyChanged(nameof(CheckedMembers)); } if (e.PropertyName == nameof(MemberSymbolViewModel.IsMakeAbstractCheckable)) { NotifyPropertyChanged(nameof(ShowMakeAbstract)); } } public void SelectPublic() => SelectMembers(Members.WhereAsArray(v => v.Symbol.DeclaredAccessibility == Accessibility.Public)); public void SelectAll() => SelectMembers(Members); internal void DeselectAll() => SelectMembers(Members, isChecked: false); public void SelectDependents() { Contract.ThrowIfFalse(ShowCheckDependentsButton); var checkedMembers = Members .WhereAsArray(member => member.IsChecked && member.IsCheckable); var result = _uiThreadOperationExecutor.Execute( title: ServicesVSResources.Pull_Members_Up, defaultDescription: ServicesVSResources.Calculating_dependents, allowCancellation: true, showProgress: true, context => { foreach (var member in Members) { _symbolToDependentsMap[member.Symbol].Wait(context.UserCancellationToken); } }); if (result == UIThreadOperationStatus.Completed) { foreach (var member in checkedMembers) { var membersToSelected = FindDependentsRecursively(member.Symbol).SelectAsArray(symbol => _symbolToMemberViewMap[symbol]); SelectMembers(membersToSelected); } } } public ImmutableArray<(ISymbol member, bool makeAbstract)> GetSelectedMembers() => Members. Where(memberSymbolView => memberSymbolView.IsChecked && memberSymbolView.IsCheckable). SelectAsArray(memberViewModel => (member: memberViewModel.Symbol, makeAbstract: memberViewModel.IsMakeAbstractCheckable && memberViewModel.MakeAbstract)); public void UpdateMembersBasedOnDestinationKind(TypeKind destinationType) { var fields = Members.WhereAsArray(memberViewModel => memberViewModel.Symbol.IsKind(SymbolKind.Field)); var makeAbstractEnabledCheckboxes = Members. WhereAsArray(memberViewModel => !memberViewModel.Symbol.IsKind(SymbolKind.Field) && !memberViewModel.Symbol.IsAbstract); var isInterface = destinationType == TypeKind.Interface; // Disable field check box and make abstract if destination is interface foreach (var member in fields) { member.IsCheckable = !isInterface; member.TooltipText = isInterface ? ServicesVSResources.Interface_cannot_have_field : string.Empty; } foreach (var member in makeAbstractEnabledCheckboxes) { member.IsMakeAbstractCheckable = !isInterface; } } private static void SelectMembers(ImmutableArray<MemberSymbolViewModel> members, bool isChecked = true) { foreach (var member in members.Where(viewModel => viewModel.IsCheckable)) { member.IsChecked = isChecked; } } private ImmutableHashSet<ISymbol> FindDependentsRecursively(ISymbol member) { var queue = new Queue<ISymbol>(); // Under situation like two methods call each other, this hashset is used to // prevent the infinity loop. var visited = new HashSet<ISymbol>(); var result = new HashSet<ISymbol>(); queue.Enqueue(member); visited.Add(member); while (!queue.IsEmpty()) { var currentMember = queue.Dequeue(); result.Add(currentMember); visited.Add(currentMember); foreach (var dependent in _symbolToDependentsMap[currentMember].Result) { if (!visited.Contains(dependent)) { queue.Enqueue(dependent); } } } return result.ToImmutableHashSet(); } } }
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/CommonControls/NewTypeDestinationSelection.xaml
<UserControl x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls.NewTypeDestinationSelection" x:ClassModifier="internal" x:Name="control" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls" xmlns:u="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Utilities" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <UserControl.Resources> <u:EnumBoolConverter x:Key="enumBoolConverter" /> <Style TargetType="ListBoxItem"> <Setter Property="IsTabStop" Value="False" /> </Style> <Thickness x:Key="labelPadding">0, 5, 0, 2</Thickness> <Thickness x:Key="okCancelButtonPadding">9,2,9,2</Thickness> <Thickness x:Key="selectDeselectButtonPadding">9,2,9,2</Thickness> <Thickness x:Key="textboxPadding">2</Thickness> <Thickness x:Key="radioButtonPadding">2, 0, 2, 0</Thickness> </UserControl.Resources> <StackPanel> <Label x:Uid="TypeNameLabel" x:Name="TypeNameLabel" Content="{Binding ElementName=control, Path=NewTypeName}" Padding="{StaticResource ResourceKey=labelPadding}" Target="{Binding ElementName=TypeNameTextBox}"/> <TextBox x:Uid="TypeNameTextBox" AutomationProperties.LabeledBy="{Binding ElementName=TypeNameLabel}" Text="{Binding TypeName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Name="TypeNameTextBox" Padding="{StaticResource ResourceKey=textboxPadding}" GotFocus="SelectAllInTextBox" /> <Label x:Uid="GeneratedNameLabel" x:Name="GeneratedNameLabel" Content="{Binding ElementName=control, Path=GeneratedName}" Padding="{StaticResource ResourceKey=labelPadding}"/> <TextBox x:Uid="GeneratedNameTextBox" AutomationProperties.LabeledBy="{Binding ElementName=GeneratedNameLabel}" Text="{Binding GeneratedName, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="True" Background="{DynamicResource {x:Static SystemColors.ControlBrush}}" Padding="{StaticResource ResourceKey=textboxPadding}" KeyboardNavigation.IsTabStop="False" /> <GroupBox x:Uid="DestinationSelectionGroupBox" Margin="0, 9, 0, 0" Header="{Binding ElementName=control, Path=SelectDestinationFile}"> <Grid Margin="9, 9, 9, 7"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition /> </Grid.ColumnDefinitions> <RadioButton x:Uid="DestinationCurrentFileSelectionRadioButton" Name="DestinationCurrentFileSelectionRadioButton" GroupName="FileDestination" Grid.Row="0" Grid.ColumnSpan="2" Margin="0, 0, 0, 5" Content="{Binding ElementName=control, Path=SelectCurrentFileAsDestination}" Padding="{StaticResource ResourceKey=radioButtonPadding}" IsChecked="{Binding Destination, Converter={StaticResource enumBoolConverter}, ConverterParameter={x:Static local:NewTypeDestination.CurrentFile}}" VerticalAlignment="Center" /> <RadioButton x:Uid="DestinationNewFileSelectionRadioButton" Name="DestinationNewFileSelectionRadioButton" GroupName="FileDestination" Grid.Row="1" Grid.Column="0" Content="{Binding ElementName=control, Path=SelectNewFileAsDestination}" IsChecked="{Binding Destination, Converter={StaticResource enumBoolConverter}, ConverterParameter={x:Static local:NewTypeDestination.NewFile}}" Padding="{StaticResource ResourceKey=radioButtonPadding}" VerticalAlignment="Center" /> <TextBox x:Uid="FileNameTextBox" AutomationProperties.LabeledBy="{Binding ElementName=DestinationNewFileSelectionRadioButton}" Text="{Binding FileName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Padding="{StaticResource ResourceKey=textboxPadding}" Margin="2, 0, 0, 0" Name="fileNameTextBox" IsEnabled="{Binding FileNameEnabled, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" GotFocus="SelectAllInTextBox" Grid.Column="1" Grid.Row="1" /> </Grid> </GroupBox> </StackPanel> </UserControl>
<UserControl x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls.NewTypeDestinationSelection" x:ClassModifier="internal" x:Name="control" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls" xmlns:u="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Utilities" xmlns:vs="clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Shell.15.0" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800" xmlns:vsshell="clr-namespace:Microsoft.VisualStudio.Shell;assembly=Microsoft.VisualStudio.Shell.15.0" Background="{DynamicResource {x:Static vs:ThemedDialogColors.WindowPanelBrushKey}}"> <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="../VSThemeDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> <u:EnumBoolConverter x:Key="enumBoolConverter" /> <Style TargetType="ListBoxItem"> <Setter Property="IsTabStop" Value="False" /> </Style> <Thickness x:Key="labelPadding">0, 5, 0, 2</Thickness> <Thickness x:Key="okCancelButtonPadding">9,2,9,2</Thickness> <Thickness x:Key="selectDeselectButtonPadding">9,2,9,2</Thickness> <Thickness x:Key="textboxPadding">2</Thickness> <Thickness x:Key="radioButtonPadding">2, 0, 2, 0</Thickness> </ResourceDictionary> </UserControl.Resources> <StackPanel> <Label x:Uid="TypeNameLabel" x:Name="TypeNameLabel" Content="{Binding ElementName=control, Path=NewTypeName}" Padding="{StaticResource ResourceKey=labelPadding}" Target="{Binding ElementName=TypeNameTextBox}"/> <TextBox x:Uid="TypeNameTextBox" AutomationProperties.LabeledBy="{Binding ElementName=TypeNameLabel}" Text="{Binding TypeName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Name="TypeNameTextBox" Padding="{StaticResource ResourceKey=textboxPadding}" GotFocus="SelectAllInTextBox" /> <Label x:Uid="GeneratedNameLabel" x:Name="GeneratedNameLabel" Content="{Binding ElementName=control, Path=GeneratedName}" Padding="{StaticResource ResourceKey=labelPadding}"/> <TextBox x:Uid="GeneratedNameTextBox" AutomationProperties.LabeledBy="{Binding ElementName=GeneratedNameLabel}" Text="{Binding GeneratedName, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="True" Background="{DynamicResource {x:Static SystemColors.ControlBrush}}" Padding="{StaticResource ResourceKey=textboxPadding}" KeyboardNavigation.IsTabStop="False" /> <GroupBox x:Uid="DestinationSelectionGroupBox" Margin="0, 9, 0, 0" Header="{Binding ElementName=control, Path=SelectDestinationFile}" BorderThickness="0" > <Grid Margin="9, 9, 9, 7"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition /> </Grid.ColumnDefinitions> <RadioButton x:Uid="DestinationCurrentFileSelectionRadioButton" Name="DestinationCurrentFileSelectionRadioButton" GroupName="FileDestination" Grid.Row="0" Grid.ColumnSpan="2" Margin="0, 0, 0, 5" Content="{Binding ElementName=control, Path=SelectCurrentFileAsDestination}" Padding="{StaticResource ResourceKey=radioButtonPadding}" IsChecked="{Binding Destination, Converter={StaticResource enumBoolConverter}, ConverterParameter={x:Static local:NewTypeDestination.CurrentFile}}" VerticalAlignment="Center" /> <RadioButton x:Uid="DestinationNewFileSelectionRadioButton" Name="DestinationNewFileSelectionRadioButton" GroupName="FileDestination" Grid.Row="1" Grid.Column="0" Content="{Binding ElementName=control, Path=SelectNewFileAsDestination}" IsChecked="{Binding Destination, Converter={StaticResource enumBoolConverter}, ConverterParameter={x:Static local:NewTypeDestination.NewFile}}" Padding="{StaticResource ResourceKey=radioButtonPadding}" VerticalAlignment="Center" /> <TextBox x:Uid="FileNameTextBox" AutomationProperties.LabeledBy="{Binding ElementName=DestinationNewFileSelectionRadioButton}" Text="{Binding FileName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Padding="{StaticResource ResourceKey=textboxPadding}" Margin="2, 0, 0, 0" Name="fileNameTextBox" IsEnabled="{Binding FileNameEnabled, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" GotFocus="SelectAllInTextBox" Grid.Column="1" Grid.Row="1" /> </Grid> </GroupBox> </StackPanel> </UserControl>
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/ExtractClass/ExtractClassDialog.xaml
<vs:DialogWindow x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass.ExtractClassDialog" x:Uid="PullMemberUpDialog" x:Name="dialog" x:ClassModifier="internal" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:vs="clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Shell.15.0" xmlns:controls="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls" mc:Ignorable="d" Title="{Binding ElementName=dialog, Path=ExtractClassTitle}" WindowStartupLocation="CenterOwner" Height="498" Width="500" MinHeight="498" MinWidth="510" HasDialogFrame="True" ShowInTaskbar="False" ResizeMode="CanResizeWithGrip"> <Window.Resources> <Thickness x:Key="okCancelButtonPadding">9,2,9,2</Thickness> </Window.Resources> <Grid Margin="11,6,11,11"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <controls:NewTypeDestinationSelection Grid.Row="0" ViewModel="{Binding ElementName=dialog, Path=ViewModel.DestinationViewModel}" /> <GroupBox x:Uid="MemberSelectionGroupBox" x:Name="MemberSelectionGroupBox" Margin="0, 9, 0, 0" Grid.Row="1" Header="{Binding ElementName=dialog, Path=SelectMembers}"> <ContentPresenter Content="{Binding ElementName=dialog, Path=MemberSelectionControl}" /> </GroupBox> <StackPanel Grid.Row="2" HorizontalAlignment="Right" Margin="0, 11, 0, 0" Orientation="Horizontal"> <Button x:Uid="OkButton" Name="OKButton" Content="{Binding ElementName=dialog, Path=OK}" Margin="0, 0, 0, 0" Padding="{StaticResource ResourceKey=okCancelButtonPadding}" Click="OK_Click" IsDefault="True" MinWidth="73" MinHeight="21"/> <Button x:Uid="CancelButton" Name="CancelButton" Content="{Binding ElementName=dialog, Path=Cancel}" Margin="7, 0, 0, 0" Padding="{StaticResource ResourceKey=okCancelButtonPadding}" Click="Cancel_Click" IsCancel="True" MinWidth="73" MinHeight="21"/> </StackPanel> </Grid> </vs:DialogWindow>
<vs:DialogWindow x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass.ExtractClassDialog" x:Uid="PullMemberUpDialog" x:Name="dialog" x:ClassModifier="internal" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:vs="clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Shell.15.0" xmlns:controls="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls" mc:Ignorable="d" Title="{Binding ElementName=dialog, Path=ExtractClassTitle}" WindowStartupLocation="CenterOwner" Height="498" Width="500" MinHeight="498" MinWidth="510" HasDialogFrame="True" ShowInTaskbar="False" ResizeMode="CanResizeWithGrip" Background="{DynamicResource {x:Static vs:ThemedDialogColors.WindowPanelBrushKey}}"> <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="../VSThemeDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> <Thickness x:Key="okCancelButtonPadding">9,2,9,2</Thickness> </ResourceDictionary> </Window.Resources> <Grid Margin="11,6,11,11"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <controls:NewTypeDestinationSelection Grid.Row="0" ViewModel="{Binding ElementName=dialog, Path=ViewModel.DestinationViewModel}" /> <GroupBox x:Uid="MemberSelectionGroupBox" x:Name="MemberSelectionGroupBox" Margin="0, 9, 0, 0" BorderThickness="0" Grid.Row="1" Header="{Binding ElementName=dialog, Path=SelectMembers}"> <ContentPresenter Content="{Binding ElementName=dialog, Path=MemberSelectionControl}" Margin="9, 9, 9, 7" /> </GroupBox> <StackPanel Grid.Row="2" Margin="0, 11, 0, 0" Orientation="Horizontal" HorizontalAlignment="Right"> <Button x:Uid="OkButton" Name="OKButton" Content="{Binding ElementName=dialog, Path=OK}" Margin="0, 0, 0, 0" Padding="{StaticResource ResourceKey=okCancelButtonPadding}" Click="OK_Click" IsDefault="True" MinWidth="73" MinHeight="21"/> <Button x:Uid="CancelButton" Name="CancelButton" Content="{Binding ElementName=dialog, Path=Cancel}" Margin="7, 0, 0, 0" Padding="{StaticResource ResourceKey=okCancelButtonPadding}" Click="Cancel_Click" IsCancel="True" MinWidth="73" MinHeight="21"/> </StackPanel> </Grid> </vs:DialogWindow>
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/ExtractClass/ExtractClassViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass { internal class ExtractClassViewModel { private readonly INotificationService _notificationService; public ExtractClassViewModel( IUIThreadOperationExecutor uiThreadOperationExecutor, INotificationService notificationService, ImmutableArray<PullMemberUpSymbolViewModel> memberViewModels, ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> memberToDependentsMap, string defaultTypeName, string defaultNamespace, string languageName, string typeParameterSuffix, ImmutableArray<string> conflictingNames, ISyntaxFactsService syntaxFactsService) { _notificationService = notificationService; MemberSelectionViewModel = new MemberSelectionViewModel( uiThreadOperationExecutor, memberViewModels, memberToDependentsMap, destinationTypeKind: TypeKind.Class); DestinationViewModel = new NewTypeDestinationSelectionViewModel( defaultTypeName, languageName, defaultNamespace, typeParameterSuffix, conflictingNames, syntaxFactsService); } internal bool TrySubmit() { if (!DestinationViewModel.TrySubmit(out var message)) { SendFailureNotification(message); return false; } return true; } private void SendFailureNotification(string message) => _notificationService.SendNotification(message, severity: NotificationSeverity.Information); public MemberSelectionViewModel MemberSelectionViewModel { get; } public NewTypeDestinationSelectionViewModel DestinationViewModel { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass { internal class ExtractClassViewModel { private readonly INotificationService _notificationService; public ExtractClassViewModel( IUIThreadOperationExecutor uiThreadOperationExecutor, INotificationService notificationService, ImmutableArray<MemberSymbolViewModel> memberViewModels, ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> memberToDependentsMap, string defaultTypeName, string defaultNamespace, string languageName, string typeParameterSuffix, ImmutableArray<string> conflictingNames, ISyntaxFactsService syntaxFactsService) { _notificationService = notificationService; MemberSelectionViewModel = new MemberSelectionViewModel( uiThreadOperationExecutor, memberViewModels, memberToDependentsMap, destinationTypeKind: TypeKind.Class); DestinationViewModel = new NewTypeDestinationSelectionViewModel( defaultTypeName, languageName, defaultNamespace, typeParameterSuffix, conflictingNames, syntaxFactsService); } internal bool TrySubmit() { if (!DestinationViewModel.TrySubmit(out var message)) { SendFailureNotification(message); return false; } return true; } private void SendFailureNotification(string message) => _notificationService.SendNotification(message, severity: NotificationSeverity.Information); public MemberSelectionViewModel MemberSelectionViewModel { get; } public NewTypeDestinationSelectionViewModel DestinationViewModel { get; } } }
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/ExtractClass/VisualStudioExtractClassOptionsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExtractClass; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PullMemberUp; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp; using Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass { [ExportWorkspaceService(typeof(IExtractClassOptionsService), ServiceLayer.Host), Shared] internal class VisualStudioExtractClassOptionsService : IExtractClassOptionsService { private readonly IThreadingContext _threadingContext; private readonly IGlyphService _glyphService; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly IGlobalOptionService _globalOptions; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioExtractClassOptionsService( IThreadingContext threadingContext, IGlyphService glyphService, IUIThreadOperationExecutor uiThreadOperationExecutor, IGlobalOptionService globalOptions) { _threadingContext = threadingContext; _glyphService = glyphService; _uiThreadOperationExecutor = uiThreadOperationExecutor; _globalOptions = globalOptions; } public async Task<ExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol selectedType, ImmutableArray<ISymbol> selectedMembers, CancellationToken cancellationToken) { var notificationService = document.Project.Solution.Workspace.Services.GetRequiredService<INotificationService>(); var membersInType = selectedType.GetMembers(). WhereAsArray(MemberAndDestinationValidator.IsMemberValid); var memberViewModels = membersInType .SelectAsArray(member => new PullMemberUpSymbolViewModel(member, _glyphService) { // The member(s) user selected will be checked at the beginning. IsChecked = selectedMembers.Any(SymbolEquivalenceComparer.Instance.Equals, member), MakeAbstract = false, IsMakeAbstractCheckable = !member.IsKind(SymbolKind.Field) && !member.IsAbstract, IsCheckable = true }); var memberToDependentsMap = SymbolDependentsBuilder.FindMemberToDependentsMap(membersInType, document.Project, cancellationToken); var conflictingTypeNames = selectedType.ContainingNamespace.GetAllTypes(cancellationToken).Select(t => t.Name); var candidateName = selectedType.Name + "Base"; var defaultTypeName = NameGenerator.GenerateUniqueName(candidateName, name => !conflictingTypeNames.Contains(name)); var containingNamespaceDisplay = selectedType.ContainingNamespace.IsGlobalNamespace ? string.Empty : selectedType.ContainingNamespace.ToDisplayString(); var formattingOptions = await document.GetSyntaxFormattingOptionsAsync(_globalOptions, cancellationToken).ConfigureAwait(false); var generatedNameTypeParameterSuffix = ExtractTypeHelpers.GetTypeParameterSuffix(document, formattingOptions, selectedType, membersInType, cancellationToken); var viewModel = new ExtractClassViewModel( _uiThreadOperationExecutor, notificationService, memberViewModels, memberToDependentsMap, defaultTypeName, containingNamespaceDisplay, document.Project.Language, generatedNameTypeParameterSuffix, conflictingTypeNames.ToImmutableArray(), document.GetRequiredLanguageService<ISyntaxFactsService>()); await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var dialog = new ExtractClassDialog(viewModel); var result = dialog.ShowModal(); if (result.GetValueOrDefault()) { return new ExtractClassOptions( viewModel.DestinationViewModel.FileName, viewModel.DestinationViewModel.TypeName, viewModel.DestinationViewModel.Destination == CommonControls.NewTypeDestination.CurrentFile, viewModel.MemberSelectionViewModel.CheckedMembers.SelectAsArray(m => new ExtractClassMemberAnalysisResult(m.Symbol, m.MakeAbstract))); } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExtractClass; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PullMemberUp; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass { [ExportWorkspaceService(typeof(IExtractClassOptionsService), ServiceLayer.Host), Shared] internal class VisualStudioExtractClassOptionsService : IExtractClassOptionsService { private readonly IThreadingContext _threadingContext; private readonly IGlyphService _glyphService; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly IGlobalOptionService _globalOptions; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioExtractClassOptionsService( IThreadingContext threadingContext, IGlyphService glyphService, IUIThreadOperationExecutor uiThreadOperationExecutor, IGlobalOptionService globalOptions) { _threadingContext = threadingContext; _glyphService = glyphService; _uiThreadOperationExecutor = uiThreadOperationExecutor; _globalOptions = globalOptions; } public async Task<ExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol selectedType, ImmutableArray<ISymbol> selectedMembers, CancellationToken cancellationToken) { var notificationService = document.Project.Solution.Workspace.Services.GetRequiredService<INotificationService>(); var membersInType = selectedType.GetMembers(). WhereAsArray(MemberAndDestinationValidator.IsMemberValid); var memberViewModels = membersInType .SelectAsArray(member => new MemberSymbolViewModel(member, _glyphService) { // The member(s) user selected will be checked at the beginning. IsChecked = selectedMembers.Any(SymbolEquivalenceComparer.Instance.Equals, member), MakeAbstract = false, IsMakeAbstractCheckable = !member.IsKind(SymbolKind.Field) && !member.IsAbstract, IsCheckable = true }); var memberToDependentsMap = SymbolDependentsBuilder.FindMemberToDependentsMap(membersInType, document.Project, cancellationToken); var conflictingTypeNames = selectedType.ContainingNamespace.GetAllTypes(cancellationToken).Select(t => t.Name); var candidateName = selectedType.Name + "Base"; var defaultTypeName = NameGenerator.GenerateUniqueName(candidateName, name => !conflictingTypeNames.Contains(name)); var containingNamespaceDisplay = selectedType.ContainingNamespace.IsGlobalNamespace ? string.Empty : selectedType.ContainingNamespace.ToDisplayString(); var formattingOptions = await document.GetSyntaxFormattingOptionsAsync(_globalOptions, cancellationToken).ConfigureAwait(false); var generatedNameTypeParameterSuffix = ExtractTypeHelpers.GetTypeParameterSuffix(document, formattingOptions, selectedType, membersInType, cancellationToken); var viewModel = new ExtractClassViewModel( _uiThreadOperationExecutor, notificationService, memberViewModels, memberToDependentsMap, defaultTypeName, containingNamespaceDisplay, document.Project.Language, generatedNameTypeParameterSuffix, conflictingTypeNames.ToImmutableArray(), document.GetRequiredLanguageService<ISyntaxFactsService>()); await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var dialog = new ExtractClassDialog(viewModel); var result = dialog.ShowModal(); if (result.GetValueOrDefault()) { return new ExtractClassOptions( viewModel.DestinationViewModel.FileName, viewModel.DestinationViewModel.TypeName, viewModel.DestinationViewModel.Destination == CommonControls.NewTypeDestination.CurrentFile, viewModel.MemberSelectionViewModel.CheckedMembers.SelectAsArray(m => new ExtractClassMemberAnalysisResult(m.Symbol, m.MakeAbstract))); } return null; } } }
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/ExtractInterface/ExtractInterfaceDialog.xaml
<vs:DialogWindow x:Uid="ExtractInterfaceDialog" x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface.ExtractInterfaceDialog" x:ClassModifier="internal" x:Name="dialog" xmlns:vs="clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Shell.15.0" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:u="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Utilities" xmlns:dest="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface" xmlns:controls="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls" mc:Ignorable="d" d:DesignHeight="380" d:DesignWidth="460" Height="380" Width="460" MinHeight="380" MinWidth="460" Title="{Binding ElementName=dialog, Path=ExtractInterfaceDialogTitle}" HasHelpButton="True" FocusManager.FocusedElement="{Binding ElementName=interfaceNameTextBox}" ResizeMode="CanResizeWithGrip" ShowInTaskbar="False" HasDialogFrame="True" WindowStartupLocation="CenterOwner"> <Window.Resources> <Style TargetType="ListBoxItem"> <Setter Property="IsTabStop" Value="False" /> </Style> <Thickness x:Key="labelPadding">0, 5, 0, 2</Thickness> <Thickness x:Key="okCancelButtonPadding">9,2,9,2</Thickness> <Thickness x:Key="selectDeselectButtonPadding">9,2,9,2</Thickness> <Thickness x:Key="textboxPadding">2</Thickness> <Thickness x:Key="radioButtonPadding">2, 0, 2, 0</Thickness> <u:EnumBoolConverter x:Key="enumBoolConverter" /> </Window.Resources> <Grid Margin="11,6,11,11"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <controls:NewTypeDestinationSelection x:Name="DestinationControl" Grid.Row="0" ViewModel="{Binding ElementName=dialog, Path=ViewModel.DestinationViewModel}" /> <GroupBox x:Uid="MemberSelectionGroupBox" x:Name="MemberSelectionGroupBox" Margin="0, 9, 0, 0" Grid.Row="1" Header="{Binding ElementName=dialog, Path=SelectPublicMembersToFormInterface}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <u:AutomationDelegatingListView x:Uid="MemberSelectionList" x:Name="Members" AutomationProperties.LabeledBy="{Binding ElementName=MemberSelectionGroupBox}" Grid.Column="0" Margin="9" SelectionMode="Extended" PreviewKeyDown="OnListViewPreviewKeyDown" MouseDoubleClick="OnListViewDoubleClick" ItemsSource="{Binding MemberContainers, Mode=TwoWay}"> <u:AutomationDelegatingListView.ItemTemplate x:Uid="SelectableMemberListItem"> <DataTemplate> <StackPanel Orientation="Horizontal"> <CheckBox x:Uid="SelectableMemberCheckBox" AutomationProperties.Name="{Binding SymbolAutomationText}" IsChecked="{Binding IsChecked, Mode=TwoWay}" Width="Auto" Focusable="False" AutomationProperties.AutomationId="{Binding SymbolName}"> </CheckBox> <Image x:Uid="SelectableMemberGlyph" Margin="8,0,0,0" Source="{Binding Glyph}"/> <TextBlock x:Uid="SelectableMemberName" Text="{Binding SymbolName}"/> </StackPanel> </DataTemplate> </u:AutomationDelegatingListView.ItemTemplate> </u:AutomationDelegatingListView> <StackPanel Grid.Column="1"> <Button x:Uid="SelectAllButton" Name="SelectAllButton" Content="{Binding ElementName=dialog, Path=SelectAll}" Margin="2, 9, 9, 7" Click="Select_All_Click" Padding="{StaticResource ResourceKey=selectDeselectButtonPadding}" MinWidth="73" MinHeight="21"/> <Button x:Uid="DeselectAllButton" Name="DeselectAllButton" Content="{Binding ElementName=dialog, Path=DeselectAll}" Margin="2, 0, 9, 0" Padding="{StaticResource ResourceKey=selectDeselectButtonPadding}" Click="Deselect_All_Click" MinWidth="73" MinHeight="21"/> </StackPanel> </Grid> </GroupBox> <StackPanel Grid.Row="2" HorizontalAlignment="Right" Margin="0, 11, 0, 0" Orientation="Horizontal"> <Button x:Uid="OkButton" Name="OKButton" Content="{Binding ElementName=dialog, Path=OK}" Margin="0, 0, 0, 0" Padding="{StaticResource ResourceKey=okCancelButtonPadding}" Click="OK_Click" IsDefault="True" MinWidth="73" MinHeight="21"/> <Button x:Uid="CancelButton" Name="CancelButton" Content="{Binding ElementName=dialog, Path=Cancel}" Margin="7, 0, 0, 0" Padding="{StaticResource ResourceKey=okCancelButtonPadding}" Click="Cancel_Click" IsCancel="True" MinWidth="73" MinHeight="21"/> </StackPanel> </Grid> </vs:DialogWindow>
<vs:DialogWindow x:Uid="ExtractInterfaceDialog" x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface.ExtractInterfaceDialog" x:ClassModifier="internal" x:Name="dialog" xmlns:vs="clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Shell.15.0" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:u="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Utilities" xmlns:dest="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface" xmlns:controls="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls" mc:Ignorable="d" d:DesignHeight="380" d:DesignWidth="460" Height="460" Width="460" MinHeight="460" MinWidth="460" Title="{Binding ElementName=dialog, Path=ExtractInterfaceDialogTitle}" HasHelpButton="True" FocusManager.FocusedElement="{Binding ElementName=interfaceNameTextBox}" ResizeMode="CanResizeWithGrip" ShowInTaskbar="False" HasDialogFrame="True" WindowStartupLocation="CenterOwner" Background="{DynamicResource {x:Static vs:ThemedDialogColors.WindowPanelBrushKey}}"> <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="../VSThemeDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> <Style TargetType="ListBoxItem"> <Setter Property="IsTabStop" Value="False" /> </Style> <Thickness x:Key="labelPadding">0, 5, 0, 2</Thickness> <Thickness x:Key="okCancelButtonPadding">9,2,9,2</Thickness> <Thickness x:Key="selectDeselectButtonPadding">9,2,9,2</Thickness> <Thickness x:Key="textboxPadding">2</Thickness> <Thickness x:Key="radioButtonPadding">2, 0, 2, 0</Thickness> <u:EnumBoolConverter x:Key="enumBoolConverter" /> </ResourceDictionary> </Window.Resources> <Grid Margin="11,6,11,11"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <controls:NewTypeDestinationSelection x:Name="DestinationControl" Grid.Row="0" ViewModel="{Binding ElementName=dialog, Path=ViewModel.DestinationViewModel}" /> <GroupBox x:Uid="MemberSelectionGroupBox" x:Name="MemberSelectionGroupBox" Margin="0, 9, 0, 0" BorderThickness="0" Grid.Row="1" Header="{Binding ElementName=dialog, Path=SelectPublicMembersToFormInterface}"> <ContentPresenter Content="{Binding ElementName=dialog, Path=MemberSelectionControl}" Margin="9, 9, 9, 7" /> </GroupBox> <StackPanel Grid.Row="2" HorizontalAlignment="Right" Margin="0, 11, 0, 0" Orientation="Horizontal"> <Button x:Uid="OkButton" Name="OKButton" Content="{Binding ElementName=dialog, Path=OK}" Margin="0, 0, 0, 0" Padding="{StaticResource ResourceKey=okCancelButtonPadding}" Click="OK_Click" IsDefault="True" MinWidth="73" MinHeight="21"/> <Button x:Uid="CancelButton" Name="CancelButton" Content="{Binding ElementName=dialog, Path=Cancel}" Margin="7, 0, 0, 0" Padding="{StaticResource ResourceKey=okCancelButtonPadding}" Click="Cancel_Click" IsCancel="True" MinWidth="73" MinHeight="21"/> </StackPanel> </Grid> </vs:DialogWindow>
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/ExtractInterface/ExtractInterfaceDialog.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface { /// <summary> /// Interaction logic for ExtractInterfaceDialog.xaml /// </summary> internal partial class ExtractInterfaceDialog : DialogWindow { public ExtractInterfaceDialogViewModel ViewModel { get; } // Expose localized strings for binding public string ExtractInterfaceDialogTitle { get { return ServicesVSResources.Extract_Interface; } } public string NewInterfaceName { get { return ServicesVSResources.New_interface_name_colon; } } public string SelectPublicMembersToFormInterface { get { return ServicesVSResources.Select_public_members_to_form_interface; } } public string SelectAll { get { return ServicesVSResources.Select_All; } } public string DeselectAll { get { return ServicesVSResources.Deselect_All; } } public string OK { get { return ServicesVSResources.OK; } } public string Cancel { get { return ServicesVSResources.Cancel; } } // Use C# Extract Interface helpTopic for C# and VB. internal ExtractInterfaceDialog(ExtractInterfaceDialogViewModel viewModel) : base(helpTopic: "vs.csharp.refactoring.extractinterface") { ViewModel = viewModel; SetCommandBindings(); Loaded += (s, e) => MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); InitializeComponent(); DataContext = viewModel; } private void SetCommandBindings() { CommandBindings.Add(new CommandBinding( new RoutedCommand( "SelectAllClickCommand", typeof(ExtractInterfaceDialog), new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.S, ModifierKeys.Alt) })), Select_All_Click)); CommandBindings.Add(new CommandBinding( new RoutedCommand( "DeselectAllClickCommand", typeof(ExtractInterfaceDialog), new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.D, ModifierKeys.Alt) })), Deselect_All_Click)); } private void OK_Click(object sender, RoutedEventArgs e) { if (ViewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; private void Select_All_Click(object sender, RoutedEventArgs e) => ViewModel.SelectAll(); private void Deselect_All_Click(object sender, RoutedEventArgs e) => ViewModel.DeselectAll(); private void OnListViewPreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Space && e.KeyboardDevice.Modifiers == ModifierKeys.None) { ToggleCheckSelection(); e.Handled = true; } } private void OnListViewDoubleClick(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) { ToggleCheckSelection(); e.Handled = true; } } private void ToggleCheckSelection() { var selectedItems = Members.SelectedItems.OfType<ExtractInterfaceDialogViewModel.MemberSymbolViewModel>().ToArray(); var allChecked = selectedItems.All(m => m.IsChecked); foreach (var item in selectedItems) { item.IsChecked = !allChecked; } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly ExtractInterfaceDialog _dialog; public TestAccessor(ExtractInterfaceDialog dialog) => _dialog = dialog; public Button OKButton => _dialog.OKButton; public Button CancelButton => _dialog.CancelButton; public Button SelectAllButton => _dialog.SelectAllButton; public Button DeselectAllButton => _dialog.DeselectAllButton; public RadioButton DestinationCurrentFileSelectionRadioButton => _dialog.DestinationControl.DestinationCurrentFileSelectionRadioButton; public RadioButton DestinationNewFileSelectionRadioButton => _dialog.DestinationControl.DestinationNewFileSelectionRadioButton; public TextBox FileNameTextBox => _dialog.DestinationControl.fileNameTextBox; public ListView Members => _dialog.Members; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface { /// <summary> /// Interaction logic for ExtractInterfaceDialog.xaml /// </summary> internal partial class ExtractInterfaceDialog : DialogWindow { public ExtractInterfaceDialogViewModel ViewModel { get; } // Expose localized strings for binding public string ExtractInterfaceDialogTitle { get { return ServicesVSResources.Extract_Interface; } } public string NewInterfaceName { get { return ServicesVSResources.New_interface_name_colon; } } public string SelectPublicMembersToFormInterface { get { return ServicesVSResources.Select_public_members_to_form_interface; } } public string SelectAll { get { return ServicesVSResources.Select_All; } } public string DeselectAll { get { return ServicesVSResources.Deselect_All; } } public string OK { get { return ServicesVSResources.OK; } } public string Cancel { get { return ServicesVSResources.Cancel; } } public MemberSelection MemberSelectionControl { get; } // Use C# Extract Interface helpTopic for C# and VB. internal ExtractInterfaceDialog(ExtractInterfaceDialogViewModel viewModel) : base(helpTopic: "vs.csharp.refactoring.extractinterface") { ViewModel = viewModel; MemberSelectionControl = new MemberSelection(ViewModel.MemberSelectionViewModel); Loaded += (s, e) => MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); InitializeComponent(); DataContext = viewModel; } private void OK_Click(object sender, RoutedEventArgs e) { if (ViewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly ExtractInterfaceDialog _dialog; public TestAccessor(ExtractInterfaceDialog dialog) => _dialog = dialog; public Button OKButton => _dialog.OKButton; public Button CancelButton => _dialog.CancelButton; public Button SelectAllButton => _dialog.MemberSelectionControl.SelectAllButton; public Button DeselectAllButton => _dialog.MemberSelectionControl.DeselectAllButton; public RadioButton DestinationCurrentFileSelectionRadioButton => _dialog.DestinationControl.DestinationCurrentFileSelectionRadioButton; public RadioButton DestinationNewFileSelectionRadioButton => _dialog.DestinationControl.DestinationNewFileSelectionRadioButton; public TextBox FileNameTextBox => _dialog.DestinationControl.fileNameTextBox; public DataGrid Members => _dialog.MemberSelectionControl.MemberSelectionGrid; } } }
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/ExtractInterface/ExtractInterfaceDialogViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface { internal class ExtractInterfaceDialogViewModel : AbstractNotifyPropertyChanged { private readonly INotificationService _notificationService; internal ExtractInterfaceDialogViewModel( ISyntaxFactsService syntaxFactsService, IGlyphService glyphService, INotificationService notificationService, string defaultInterfaceName, List<ISymbol> extractableMembers, List<string> conflictingTypeNames, string defaultNamespace, string generatedNameTypeParameterSuffix, string languageName) { _notificationService = notificationService; DestinationViewModel = new NewTypeDestinationSelectionViewModel( defaultInterfaceName, languageName, defaultNamespace, generatedNameTypeParameterSuffix, conflictingTypeNames.ToImmutableArray(), syntaxFactsService); MemberContainers = extractableMembers.Select(m => new MemberSymbolViewModel(m, glyphService)).OrderBy(s => s.SymbolName).ToList(); } internal bool TrySubmit() { if (!DestinationViewModel.TrySubmit(out var message)) { SendFailureNotification(message); return false; } if (!MemberContainers.Any(c => c.IsChecked)) { SendFailureNotification(ServicesVSResources.You_must_select_at_least_one_member); return false; } // TODO: Deal with filename already existing return true; } private void SendFailureNotification(string message) => _notificationService.SendNotification(message, severity: NotificationSeverity.Information); internal void DeselectAll() { foreach (var memberContainer in MemberContainers) { memberContainer.IsChecked = false; } } internal void SelectAll() { foreach (var memberContainer in MemberContainers) { memberContainer.IsChecked = true; } } public List<MemberSymbolViewModel> MemberContainers { get; set; } public NewTypeDestinationSelectionViewModel DestinationViewModel { get; internal set; } internal class MemberSymbolViewModel : SymbolViewModel<ISymbol> { public MemberSymbolViewModel(ISymbol symbol, IGlyphService glyphService) : base(symbol, glyphService) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface { internal class ExtractInterfaceDialogViewModel : AbstractNotifyPropertyChanged { private readonly INotificationService _notificationService; internal ExtractInterfaceDialogViewModel( ISyntaxFactsService syntaxFactsService, IUIThreadOperationExecutor uiThreadOperationExecutor, INotificationService notificationService, string defaultInterfaceName, List<string> conflictingTypeNames, ImmutableArray<LanguageServices.Utilities.MemberSymbolViewModel> memberViewModels, string defaultNamespace, string generatedNameTypeParameterSuffix, string languageName) { _notificationService = notificationService; MemberSelectionViewModel = new MemberSelectionViewModel( uiThreadOperationExecutor, memberViewModels, dependentsMap: null, destinationTypeKind: TypeKind.Interface, showDependentsButton: false, showPublicButton: false); DestinationViewModel = new NewTypeDestinationSelectionViewModel( defaultInterfaceName, languageName, defaultNamespace, generatedNameTypeParameterSuffix, conflictingTypeNames.ToImmutableArray(), syntaxFactsService); } internal bool TrySubmit() { if (!DestinationViewModel.TrySubmit(out var message)) { SendFailureNotification(message); return false; } if (!MemberContainers.Any(c => c.IsChecked)) { SendFailureNotification(ServicesVSResources.You_must_select_at_least_one_member); return false; } // TODO: Deal with filename already existing return true; } private void SendFailureNotification(string message) => _notificationService.SendNotification(message, severity: NotificationSeverity.Information); public ImmutableArray<MemberSymbolViewModel> MemberContainers => MemberSelectionViewModel.Members; public NewTypeDestinationSelectionViewModel DestinationViewModel { get; internal set; } public MemberSelectionViewModel MemberSelectionViewModel { get; } } }
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/ExtractInterface/VisualStudioExtractInterfaceOptionsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExtractInterface; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface { [ExportWorkspaceService(typeof(IExtractInterfaceOptionsService), ServiceLayer.Host), Shared] internal class VisualStudioExtractInterfaceOptionsService : IExtractInterfaceOptionsService { private readonly IGlyphService _glyphService; private readonly IThreadingContext _threadingContext; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioExtractInterfaceOptionsService(IGlyphService glyphService, IThreadingContext threadingContext) { _glyphService = glyphService; _threadingContext = threadingContext; } public async Task<ExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync( ISyntaxFactsService syntaxFactsService, INotificationService notificationService, List<ISymbol> extractableMembers, string defaultInterfaceName, List<string> allTypeNames, string defaultNamespace, string generatedNameTypeParameterSuffix, string languageName, CleanCodeGenerationOptionsProvider fallbackOptions, CancellationToken cancellationToken) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var viewModel = new ExtractInterfaceDialogViewModel( syntaxFactsService, _glyphService, notificationService, defaultInterfaceName, extractableMembers, allTypeNames, defaultNamespace, generatedNameTypeParameterSuffix, languageName); var dialog = new ExtractInterfaceDialog(viewModel); var result = dialog.ShowModal(); if (result.HasValue && result.Value) { var includedMembers = viewModel.MemberContainers.Where(c => c.IsChecked).Select(c => c.Symbol); return new ExtractInterfaceOptionsResult( isCancelled: false, includedMembers: includedMembers.AsImmutable(), interfaceName: viewModel.DestinationViewModel.TypeName.Trim(), fileName: viewModel.DestinationViewModel.FileName.Trim(), location: GetLocation(viewModel.DestinationViewModel.Destination), fallbackOptions); } else { return ExtractInterfaceOptionsResult.Cancelled; } } private static ExtractInterfaceOptionsResult.ExtractLocation GetLocation(NewTypeDestination destination) { switch (destination) { case NewTypeDestination.CurrentFile: return ExtractInterfaceOptionsResult.ExtractLocation.SameFile; case NewTypeDestination.NewFile: return ExtractInterfaceOptionsResult.ExtractLocation.NewFile; default: throw ExceptionUtilities.UnexpectedValue(destination); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExtractInterface; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface { [ExportWorkspaceService(typeof(IExtractInterfaceOptionsService), ServiceLayer.Host), Shared] internal class VisualStudioExtractInterfaceOptionsService : IExtractInterfaceOptionsService { private readonly IGlyphService _glyphService; private readonly IThreadingContext _threadingContext; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioExtractInterfaceOptionsService(IGlyphService glyphService, IThreadingContext threadingContext, IUIThreadOperationExecutor uiThreadOperationExecutor) { _glyphService = glyphService; _threadingContext = threadingContext; _uiThreadOperationExecutor = uiThreadOperationExecutor; } public async Task<ExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync( ISyntaxFactsService syntaxFactsService, INotificationService notificationService, List<ISymbol> extractableMembers, string defaultInterfaceName, List<string> allTypeNames, string defaultNamespace, string generatedNameTypeParameterSuffix, string languageName, CleanCodeGenerationOptionsProvider fallbackOptions, CancellationToken cancellationToken) { using var cancellationTokenSource = new CancellationTokenSource(); var memberViewModels = extractableMembers .SelectAsArray(member => new MemberSymbolViewModel(member, _glyphService) { IsChecked = true, MakeAbstract = false, IsMakeAbstractCheckable = false, IsCheckable = true }); await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var viewModel = new ExtractInterfaceDialogViewModel( syntaxFactsService, _uiThreadOperationExecutor, notificationService, defaultInterfaceName, allTypeNames, memberViewModels, defaultNamespace, generatedNameTypeParameterSuffix, languageName); var dialog = new ExtractInterfaceDialog(viewModel); var result = dialog.ShowModal(); if (result.HasValue && result.Value) { var includedMembers = viewModel.MemberContainers.Where(c => c.IsChecked).Select(c => c.Symbol); return new ExtractInterfaceOptionsResult( isCancelled: false, includedMembers: includedMembers.AsImmutable(), interfaceName: viewModel.DestinationViewModel.TypeName.Trim(), fileName: viewModel.DestinationViewModel.FileName.Trim(), location: GetLocation(viewModel.DestinationViewModel.Destination), fallbackOptions); } else { return ExtractInterfaceOptionsResult.Cancelled; } } private static ExtractInterfaceOptionsResult.ExtractLocation GetLocation(NewTypeDestination destination) => destination switch { NewTypeDestination.CurrentFile => ExtractInterfaceOptionsResult.ExtractLocation.SameFile, NewTypeDestination.NewFile => ExtractInterfaceOptionsResult.ExtractLocation.NewFile, _ => throw ExceptionUtilities.UnexpectedValue(destination), }; } }
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/PickMembers/PickMembersDialog.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers { /// <summary> /// Interaction logic for ExtractInterfaceDialog.xaml /// </summary> internal partial class PickMembersDialog : DialogWindow { private readonly PickMembersDialogViewModel _viewModel; // Expose localized strings for binding public string PickMembersDialogTitle => ServicesVSResources.Pick_members; public string PickMembersTitle { get; } public string SelectAll => ServicesVSResources.Select_All; public string DeselectAll => ServicesVSResources.Deselect_All; public string OK => ServicesVSResources.OK; public string Cancel => ServicesVSResources.Cancel; internal PickMembersDialog(PickMembersDialogViewModel viewModel, string title) { PickMembersTitle = title; _viewModel = viewModel; SetCommandBindings(); InitializeComponent(); DataContext = viewModel; } private void SetCommandBindings() { CommandBindings.Add(new CommandBinding( new RoutedCommand( "SelectAllClickCommand", typeof(PickMembersDialog), new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.S, ModifierKeys.Alt) })), Select_All_Click)); CommandBindings.Add(new CommandBinding( new RoutedCommand( "DeselectAllClickCommand", typeof(PickMembersDialog), new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.D, ModifierKeys.Alt) })), Deselect_All_Click)); } private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e) { _viewModel.Filter(SearchTextBox.Text); Members.Items.Refresh(); } private void OK_Click(object sender, RoutedEventArgs e) => DialogResult = true; private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; private void Select_All_Click(object sender, RoutedEventArgs e) => _viewModel.SelectAll(); private void Deselect_All_Click(object sender, RoutedEventArgs e) => _viewModel.DeselectAll(); private void MoveUp_Click(object sender, EventArgs e) { var oldSelectedIndex = Members.SelectedIndex; if (_viewModel.CanMoveUp && oldSelectedIndex >= 0) { _viewModel.MoveUp(); Members.Items.Refresh(); Members.SelectedIndex = oldSelectedIndex - 1; } SetFocusToSelectedRow(); } private void MoveDown_Click(object sender, EventArgs e) { var oldSelectedIndex = Members.SelectedIndex; if (_viewModel.CanMoveDown && oldSelectedIndex >= 0) { _viewModel.MoveDown(); Members.Items.Refresh(); Members.SelectedIndex = oldSelectedIndex + 1; } SetFocusToSelectedRow(); } private void SetFocusToSelectedRow() { if (Members.SelectedIndex >= 0) { if (Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) is not ListViewItem row) { Members.ScrollIntoView(Members.SelectedItem); row = Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) as ListViewItem; } row?.Focus(); } } private void OnListViewPreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Space && e.KeyboardDevice.Modifiers == ModifierKeys.None) { ToggleCheckSelection(); e.Handled = true; } } private void OnListViewDoubleClick(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) { ToggleCheckSelection(); e.Handled = true; } } private void ToggleCheckSelection() { var selectedItems = Members.SelectedItems.OfType<PickMembersDialogViewModel.MemberSymbolViewModel>().ToArray(); var allChecked = selectedItems.All(m => m.IsChecked); foreach (var item in selectedItems) { item.IsChecked = !allChecked; } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly PickMembersDialog _dialog; public TestAccessor(PickMembersDialog dialog) => _dialog = dialog; public Button OKButton => _dialog.OKButton; public Button CancelButton => _dialog.CancelButton; public Button UpButton => _dialog.UpButton; public Button DownButton => _dialog.DownButton; public AutomationDelegatingListView Members => _dialog.Members; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers { /// <summary> /// Interaction logic for ExtractInterfaceDialog.xaml /// </summary> internal partial class PickMembersDialog : DialogWindow { private readonly PickMembersDialogViewModel _viewModel; // Expose localized strings for binding public string PickMembersDialogTitle => ServicesVSResources.Pick_members; public string PickMembersTitle { get; } public string SelectAll => ServicesVSResources.Select_All; public string DeselectAll => ServicesVSResources.Deselect_All; public string OK => ServicesVSResources.OK; public string Cancel => ServicesVSResources.Cancel; internal PickMembersDialog(PickMembersDialogViewModel viewModel, string title) { PickMembersTitle = title; _viewModel = viewModel; SetCommandBindings(); InitializeComponent(); DataContext = viewModel; } private void SetCommandBindings() { CommandBindings.Add(new CommandBinding( new RoutedCommand( "SelectAllClickCommand", typeof(PickMembersDialog), new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.S, ModifierKeys.Alt) })), Select_All_Click)); CommandBindings.Add(new CommandBinding( new RoutedCommand( "DeselectAllClickCommand", typeof(PickMembersDialog), new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.D, ModifierKeys.Alt) })), Deselect_All_Click)); } private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e) { _viewModel.Filter(SearchTextBox.Text); Members.Items.Refresh(); } private void OK_Click(object sender, RoutedEventArgs e) => DialogResult = true; private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; private void Select_All_Click(object sender, RoutedEventArgs e) => _viewModel.SelectAll(); private void Deselect_All_Click(object sender, RoutedEventArgs e) => _viewModel.DeselectAll(); private void MoveUp_Click(object sender, EventArgs e) { var oldSelectedIndex = Members.SelectedIndex; if (_viewModel.CanMoveUp && oldSelectedIndex >= 0) { _viewModel.MoveUp(); Members.Items.Refresh(); Members.SelectedIndex = oldSelectedIndex - 1; } SetFocusToSelectedRow(); } private void MoveDown_Click(object sender, EventArgs e) { var oldSelectedIndex = Members.SelectedIndex; if (_viewModel.CanMoveDown && oldSelectedIndex >= 0) { _viewModel.MoveDown(); Members.Items.Refresh(); Members.SelectedIndex = oldSelectedIndex + 1; } SetFocusToSelectedRow(); } private void SetFocusToSelectedRow() { if (Members.SelectedIndex >= 0) { if (Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) is not ListViewItem row) { Members.ScrollIntoView(Members.SelectedItem); row = Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) as ListViewItem; } row?.Focus(); } } private void OnListViewPreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Space && e.KeyboardDevice.Modifiers == ModifierKeys.None) { ToggleCheckSelection(); e.Handled = true; } } private void OnListViewDoubleClick(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) { ToggleCheckSelection(); e.Handled = true; } } private void ToggleCheckSelection() { var selectedItems = Members.SelectedItems.OfType<MemberSymbolViewModel>().ToArray(); var allChecked = selectedItems.All(m => m.IsChecked); foreach (var item in selectedItems) { item.IsChecked = !allChecked; } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly PickMembersDialog _dialog; public TestAccessor(PickMembersDialog dialog) => _dialog = dialog; public Button OKButton => _dialog.OKButton; public Button CancelButton => _dialog.CancelButton; public Button UpButton => _dialog.UpButton; public Button DownButton => _dialog.DownButton; public AutomationDelegatingListView Members => _dialog.Members; } } }
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/PickMembers/PickMembersDialogViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers { internal class PickMembersDialogViewModel : AbstractNotifyPropertyChanged { private readonly List<MemberSymbolViewModel> _allMembers; public List<MemberSymbolViewModel> MemberContainers { get; set; } public List<OptionViewModel> Options { get; set; } /// <summary> /// <see langword="true"/> if 'Select All' was chosen. <see langword="false"/> if 'Deselect All' was chosen. /// </summary> public bool SelectedAll { get; set; } internal PickMembersDialogViewModel( IGlyphService glyphService, ImmutableArray<ISymbol> members, ImmutableArray<PickMembersOption> options, bool selectAll) { _allMembers = members.Select(m => new MemberSymbolViewModel(m, glyphService)).ToList(); MemberContainers = _allMembers; Options = options.Select(o => new OptionViewModel(o)).ToList(); if (selectAll) { SelectAll(); } else { DeselectAll(); } } internal void Filter(string searchText) { searchText = searchText.Trim(); MemberContainers = searchText.Length == 0 ? _allMembers : _allMembers.Where(m => m.SymbolAutomationText.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0).ToList(); NotifyPropertyChanged(nameof(MemberContainers)); } internal void DeselectAll() { SelectedAll = false; foreach (var memberContainer in MemberContainers) memberContainer.IsChecked = false; } internal void SelectAll() { SelectedAll = true; foreach (var memberContainer in MemberContainers) memberContainer.IsChecked = true; } private int? _selectedIndex; public int? SelectedIndex { get { return _selectedIndex; } set { var newSelectedIndex = value == -1 ? null : value; if (newSelectedIndex == _selectedIndex) { return; } _selectedIndex = newSelectedIndex; NotifyPropertyChanged(nameof(CanMoveUp)); NotifyPropertyChanged(nameof(MoveUpAutomationText)); NotifyPropertyChanged(nameof(CanMoveDown)); NotifyPropertyChanged(nameof(MoveDownAutomationText)); } } public string MoveUpAutomationText { get { if (!CanMoveUp) { return string.Empty; } return string.Format(ServicesVSResources.Move_0_above_1, MemberContainers[SelectedIndex.Value].SymbolAutomationText, MemberContainers[SelectedIndex.Value - 1].SymbolAutomationText); } } public string MoveDownAutomationText { get { if (!CanMoveDown) { return string.Empty; } return string.Format(ServicesVSResources.Move_0_below_1, MemberContainers[SelectedIndex.Value].SymbolAutomationText, MemberContainers[SelectedIndex.Value + 1].SymbolAutomationText); } } [MemberNotNullWhen(true, nameof(SelectedIndex))] public bool CanMoveUp { get { if (!SelectedIndex.HasValue) { return false; } var index = SelectedIndex.Value; return index > 0; } } [MemberNotNullWhen(true, nameof(SelectedIndex))] public bool CanMoveDown { get { if (!SelectedIndex.HasValue) { return false; } var index = SelectedIndex.Value; return index < MemberContainers.Count - 1; } } internal void MoveUp() { Contract.ThrowIfFalse(CanMoveUp); var index = SelectedIndex.Value; Move(MemberContainers, index, delta: -1); } internal void MoveDown() { Contract.ThrowIfFalse(CanMoveDown); var index = SelectedIndex.Value; Move(MemberContainers, index, delta: 1); } private void Move(List<MemberSymbolViewModel> list, int index, int delta) { var param = list[index]; list.RemoveAt(index); list.Insert(index + delta, param); SelectedIndex += delta; } internal class MemberSymbolViewModel : SymbolViewModel<ISymbol> { public MemberSymbolViewModel(ISymbol symbol, IGlyphService glyphService) : base(symbol, glyphService) { } } internal class OptionViewModel : AbstractNotifyPropertyChanged { public PickMembersOption Option { get; } public string Title { get; } public OptionViewModel(PickMembersOption option) { Option = option; Title = option.Title; IsChecked = option.Value; } private bool _isChecked; public bool IsChecked { get => _isChecked; set { Option.Value = value; SetProperty(ref _isChecked, value); } } public string MemberAutomationText => Option.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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.LanguageServices.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers { internal class PickMembersDialogViewModel : AbstractNotifyPropertyChanged { private readonly List<MemberSymbolViewModel> _allMembers; public List<MemberSymbolViewModel> MemberContainers { get; set; } public List<OptionViewModel> Options { get; set; } /// <summary> /// <see langword="true"/> if 'Select All' was chosen. <see langword="false"/> if 'Deselect All' was chosen. /// </summary> public bool SelectedAll { get; set; } internal PickMembersDialogViewModel( IGlyphService glyphService, ImmutableArray<ISymbol> members, ImmutableArray<PickMembersOption> options, bool selectAll) { _allMembers = members.Select(m => new MemberSymbolViewModel(m, glyphService)).ToList(); MemberContainers = _allMembers; Options = options.Select(o => new OptionViewModel(o)).ToList(); if (selectAll) { SelectAll(); } else { DeselectAll(); } } internal void Filter(string searchText) { searchText = searchText.Trim(); MemberContainers = searchText.Length == 0 ? _allMembers : _allMembers.Where(m => m.SymbolAutomationText.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0).ToList(); NotifyPropertyChanged(nameof(MemberContainers)); } internal void DeselectAll() { SelectedAll = false; foreach (var memberContainer in MemberContainers) memberContainer.IsChecked = false; } internal void SelectAll() { SelectedAll = true; foreach (var memberContainer in MemberContainers) memberContainer.IsChecked = true; } private int? _selectedIndex; public int? SelectedIndex { get { return _selectedIndex; } set { var newSelectedIndex = value == -1 ? null : value; if (newSelectedIndex == _selectedIndex) { return; } _selectedIndex = newSelectedIndex; NotifyPropertyChanged(nameof(CanMoveUp)); NotifyPropertyChanged(nameof(MoveUpAutomationText)); NotifyPropertyChanged(nameof(CanMoveDown)); NotifyPropertyChanged(nameof(MoveDownAutomationText)); } } public string MoveUpAutomationText { get { if (!CanMoveUp) { return string.Empty; } return string.Format(ServicesVSResources.Move_0_above_1, MemberContainers[SelectedIndex.Value].SymbolAutomationText, MemberContainers[SelectedIndex.Value - 1].SymbolAutomationText); } } public string MoveDownAutomationText { get { if (!CanMoveDown) { return string.Empty; } return string.Format(ServicesVSResources.Move_0_below_1, MemberContainers[SelectedIndex.Value].SymbolAutomationText, MemberContainers[SelectedIndex.Value + 1].SymbolAutomationText); } } [MemberNotNullWhen(true, nameof(SelectedIndex))] public bool CanMoveUp { get { if (!SelectedIndex.HasValue) { return false; } var index = SelectedIndex.Value; return index > 0; } } [MemberNotNullWhen(true, nameof(SelectedIndex))] public bool CanMoveDown { get { if (!SelectedIndex.HasValue) { return false; } var index = SelectedIndex.Value; return index < MemberContainers.Count - 1; } } internal void MoveUp() { Contract.ThrowIfFalse(CanMoveUp); var index = SelectedIndex.Value; Move(MemberContainers, index, delta: -1); } internal void MoveDown() { Contract.ThrowIfFalse(CanMoveDown); var index = SelectedIndex.Value; Move(MemberContainers, index, delta: 1); } private void Move(List<MemberSymbolViewModel> list, int index, int delta) { var param = list[index]; list.RemoveAt(index); list.Insert(index + delta, param); SelectedIndex += delta; } internal class OptionViewModel : AbstractNotifyPropertyChanged { public PickMembersOption Option { get; } public string Title { get; } public OptionViewModel(PickMembersOption option) { Option = option; Title = option.Title; IsChecked = option.Value; } private bool _isChecked; public bool IsChecked { get => _isChecked; set { Option.Value = value; SetProperty(ref _isChecked, value); } } public string MemberAutomationText => Option.Title; } } }
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/PullMemberUp/MainDialog/PullMemberUpDialog.xaml
<vs:DialogWindow x:Uid="PullMemberUpDialog" x:Name="dialog" x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog.PullMemberUpDialog" x:ClassModifier="internal" xmlns:vs="clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Shell.15.0" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:self="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog" mc:Ignorable="d" WindowStartupLocation="CenterOwner" Height="498" Width="500" MinHeight="498" MinWidth="510" HasDialogFrame="True" ShowInTaskbar="False" ResizeMode="CanResizeWithGrip" Title="{Binding ElementName=dialog, Path=PullMembersUpTitle}"> <Window.Resources> <Thickness x:Key="ButtonPadding">9, 2, 9, 2</Thickness> <sys:Double x:Key="ButtonWidth">73</sys:Double> <sys:Double x:Key="ButtonHeight">21</sys:Double> <Style x:Key="TreeViewItemStyle" TargetType="{x:Type TreeViewItem}"> <Setter Property="IsSelected" Value="{Binding IsChecked, Mode=TwoWay}"/> <Setter Property="FontWeight" Value="Normal" /> <Setter Property="AutomationProperties.Name" Value="{Binding SymbolAutomationText}"/> <Setter Property="AutomationProperties.AutomationId" Value="{Binding SymbolName}"/> <Setter Property="IsExpanded" Value="True"/> <Style.Resources> <Style TargetType="{x:Type Border}"> <Setter Property="Grid.ColumnSpan" Value="2"/> </Style> </Style.Resources> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/> <Setter Property="FontWeight" Value="Bold"/> </Trigger> </Style.Triggers> </Style> </Window.Resources> <Grid Margin="12"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="40*"/> <RowDefinition Height="60*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Label Grid.Row="0" x:Uid="TitleDescription" x:Name="TitleDescription" Margin="0,0,0,12" Content="{Binding ElementName=dialog, Path=Description}"/> <GroupBox x:Uid="DestinationSelectionGroupBox" x:Name="DestinationSelectionGroupBox" Grid.Row="1" BorderThickness="0" MinHeight="130" Header="{Binding ElementName=dialog, Path=SelectDestination}"> <TreeView x:Uid="DestinationTreeView" x:Name="DestinationTreeView" MinHeight="100" MinWidth="360" Margin="0, 5, 0, 0" AutomationProperties.Name="{Binding DestinationTreeViewAutomationText}" ScrollViewer.VerticalScrollBarVisibility="Auto" ItemsSource="{Binding DestinationTreeNodeViewModel.BaseTypeNodes}" ItemContainerStyle="{StaticResource TreeViewItemStyle}" SelectedItemChanged="Destination_SelectedItemChanged"> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding BaseTypeNodes}" DataType="{x:Type self:BaseTypeTreeNodeViewModel}"> <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Focusable="False" VerticalAlignment="Stretch"> <Image Source="{Binding Glyph}" Margin="0, 0, 5, 0" /> <TextBlock x:Uid="DestinationTextBlock" Text="{Binding SymbolName}" ToolTip="{Binding Namespace}"/> </StackPanel> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> </GroupBox> <GroupBox x:Uid="MemberSelectionLabel" Header="{Binding ElementName=dialog, Path=SelectMembers}" Grid.Row="2" MinHeight="200" MinWidth="250" BorderThickness="0"> <ContentControl Content="{Binding ElementName=dialog, Path=MemberSelectionControl}" /> </GroupBox> <StackPanel Grid.Row="3" Margin="0, 5, 6, 0" HorizontalAlignment="Right" Orientation="Horizontal"> <Button x:Name="OKButton" x:Uid="OKButton" Click="OKButton_Click" IsDefault="True" Margin="0" IsEnabled="{Binding OkButtonEnabled, UpdateSourceTrigger=PropertyChanged}" Padding="{StaticResource ResourceKey=ButtonPadding}" Content="{Binding OK, ElementName=dialog}" MinWidth="{StaticResource ResourceKey=ButtonWidth}" MinHeight="{StaticResource ResourceKey=ButtonHeight}"/> <Button x:Name="CancelButton" x:Uid="CancelButton" Click="CancelButton_Click" IsCancel="True" Padding="{StaticResource ResourceKey=ButtonPadding}" Margin="7, 0, 0, 0" Content="{Binding Cancel, ElementName=dialog}" MinWidth="{StaticResource ResourceKey=ButtonWidth}" MinHeight="{StaticResource ResourceKey=ButtonHeight}"/> </StackPanel> </Grid> </vs:DialogWindow>
<vs:DialogWindow x:Uid="PullMemberUpDialog" x:Name="dialog" x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog.PullMemberUpDialog" x:ClassModifier="internal" xmlns:vs="clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Shell.15.0" xmlns:vsshell="clr-namespace:Microsoft.VisualStudio.Shell;assembly=Microsoft.VisualStudio.Shell.15.0" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:self="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog" mc:Ignorable="d" WindowStartupLocation="CenterOwner" Height="498" Width="500" MinHeight="498" MinWidth="510" HasDialogFrame="True" ShowInTaskbar="False" ResizeMode="CanResizeWithGrip" Title="{Binding ElementName=dialog, Path=PullMembersUpTitle}" Background="{DynamicResource {x:Static vs:ThemedDialogColors.WindowPanelBrushKey}}"> <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="../../VSThemeDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> <Thickness x:Key="ButtonPadding">9, 2, 9, 2</Thickness> <sys:Double x:Key="ButtonWidth">73</sys:Double> <sys:Double x:Key="ButtonHeight">21</sys:Double> <Style x:Key="TreeViewItemStyle" TargetType="{x:Type TreeViewItem}"> <Setter Property="IsSelected" Value="{Binding IsChecked, Mode=TwoWay}"/> <Setter Property="FontWeight" Value="Normal" /> <Setter Property="AutomationProperties.Name" Value="{Binding SymbolAutomationText}"/> <Setter Property="AutomationProperties.AutomationId" Value="{Binding SymbolName}"/> <Setter Property="IsExpanded" Value="True"/> <Style.Resources> <Style TargetType="{x:Type Border}"> <Setter Property="Grid.ColumnSpan" Value="2"/> </Style> </Style.Resources> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/> <Setter Property="FontWeight" Value="Bold"/> </Trigger> </Style.Triggers> </Style> </ResourceDictionary> </Window.Resources> <Grid Margin="12"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="40*"/> <RowDefinition Height="60*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Label Grid.Row="0" x:Uid="TitleDescription" x:Name="TitleDescription" Margin="0,0,0,12" Content="{Binding ElementName=dialog, Path=Description}"/> <GroupBox x:Uid="DestinationSelectionGroupBox" x:Name="DestinationSelectionGroupBox" Grid.Row="1" BorderThickness="0" MinHeight="130" Header="{Binding ElementName=dialog, Path=SelectDestination}"> <TreeView x:Uid="DestinationTreeView" x:Name="DestinationTreeView" MinHeight="100" MinWidth="360" Margin="0, 5, 0, 0" AutomationProperties.Name="{Binding DestinationTreeViewAutomationText}" ScrollViewer.VerticalScrollBarVisibility="Auto" ItemsSource="{Binding DestinationTreeNodeViewModel.BaseTypeNodes}" ItemContainerStyle="{StaticResource TreeViewItemStyle}" SelectedItemChanged="Destination_SelectedItemChanged"> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding BaseTypeNodes}" DataType="{x:Type self:BaseTypeTreeNodeViewModel}"> <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Focusable="False" VerticalAlignment="Stretch"> <Image Source="{Binding Glyph}" Margin="0, 0, 5, 0" /> <TextBlock x:Uid="DestinationTextBlock" Text="{Binding SymbolName}" ToolTip="{Binding Namespace}"> <TextBlock.Style> <Style TargetType="TextBlock"> <Setter Property="Foreground" Value="{DynamicResource {x:Static vsshell:VsBrushes.ToolWindowTextKey}}" /> <Setter Property="Background" Value="Transparent" /> </Style> </TextBlock.Style> </TextBlock> </StackPanel> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> </GroupBox> <GroupBox x:Uid="MemberSelectionLabel" Header="{Binding ElementName=dialog, Path=SelectMembers}" Grid.Row="2" MinHeight="200" MinWidth="250" BorderThickness="0"> <ContentControl Content="{Binding ElementName=dialog, Path=MemberSelectionControl}" /> </GroupBox> <StackPanel Grid.Row="3" Margin="0, 5, 6, 0" HorizontalAlignment="Right" Orientation="Horizontal"> <Button x:Name="OKButton" x:Uid="OKButton" Click="OKButton_Click" IsDefault="True" Margin="0" IsEnabled="{Binding OkButtonEnabled, UpdateSourceTrigger=PropertyChanged}" Padding="{StaticResource ResourceKey=ButtonPadding}" Content="{Binding OK, ElementName=dialog}" MinWidth="{StaticResource ResourceKey=ButtonWidth}" MinHeight="{StaticResource ResourceKey=ButtonHeight}"/> <Button x:Name="CancelButton" x:Uid="CancelButton" Click="CancelButton_Click" IsCancel="True" Padding="{StaticResource ResourceKey=ButtonPadding}" Margin="7, 0, 0, 0" Content="{Binding Cancel, ElementName=dialog}" MinWidth="{StaticResource ResourceKey=ButtonWidth}" MinHeight="{StaticResource ResourceKey=ButtonHeight}"/> </StackPanel> </Grid> </vs:DialogWindow>
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/PullMemberUp/MainDialog/PullMemberUpDialogViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.PullMemberUp; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog { internal class PullMemberUpDialogViewModel : AbstractNotifyPropertyChanged { public bool OkButtonEnabled { get => _okButtonEnabled; set => SetProperty(ref _okButtonEnabled, value, nameof(OkButtonEnabled)); } public bool? SelectAllCheckBoxState { get => _selectAllCheckBoxState; set => SetProperty(ref _selectAllCheckBoxState, value, nameof(SelectAllCheckBoxState)); } public bool SelectAllCheckBoxThreeStateEnable { get => _selectAllCheckBoxThreeStateEnable; set => SetProperty(ref _selectAllCheckBoxThreeStateEnable, value, nameof(SelectAllCheckBoxThreeStateEnable)); } public string SelectAllCheckBoxAutomationText => ServicesVSResources.Select_All; public string DestinationTreeViewAutomationText => ServicesVSResources.Select_destination; public string SelectMemberListViewAutomationText => ServicesVSResources.Select_member; private bool _selectAllCheckBoxThreeStateEnable; private bool? _selectAllCheckBoxState; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> _symbolToDependentsMap; private bool _okButtonEnabled; public PullMemberUpDialogViewModel( IUIThreadOperationExecutor uiThreadOperationExecutor, ImmutableArray<PullMemberUpSymbolViewModel> members, BaseTypeTreeNodeViewModel destinationTreeViewModel, ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> dependentsMap) { _uiThreadOperationExecutor = uiThreadOperationExecutor; _symbolToDependentsMap = dependentsMap; MemberSelectionViewModel = new MemberSelectionViewModel( _uiThreadOperationExecutor, members, _symbolToDependentsMap); MemberSelectionViewModel.PropertyChanged += (s, e) => { if (e.PropertyName == nameof(MemberSelectionViewModel.CheckedMembers)) { EnableOrDisableOkButton(); } }; DestinationTreeNodeViewModel = destinationTreeViewModel; _selectedDestination = destinationTreeViewModel; EnableOrDisableOkButton(); } public BaseTypeTreeNodeViewModel DestinationTreeNodeViewModel { get; } public MemberSelectionViewModel MemberSelectionViewModel { get; } private BaseTypeTreeNodeViewModel _selectedDestination; public BaseTypeTreeNodeViewModel SelectedDestination { get => _selectedDestination; set { if (SetProperty(ref _selectedDestination, value)) { MemberSelectionViewModel.UpdateMembersBasedOnDestinationKind(_selectedDestination.Symbol.TypeKind); EnableOrDisableOkButton(); } } } public PullMembersUpOptions CreatePullMemberUpOptions() { var selectedOptionFromDialog = MemberSelectionViewModel.GetSelectedMembers(); var options = PullMembersUpOptionsBuilder.BuildPullMembersUpOptions( SelectedDestination.Symbol, selectedOptionFromDialog); return options; } private void EnableOrDisableOkButton() { var selectedMembers = MemberSelectionViewModel.CheckedMembers; OkButtonEnabled = SelectedDestination != DestinationTreeNodeViewModel && selectedMembers.Any(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.PullMemberUp; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog { internal class PullMemberUpDialogViewModel : AbstractNotifyPropertyChanged { public bool OkButtonEnabled { get => _okButtonEnabled; set => SetProperty(ref _okButtonEnabled, value, nameof(OkButtonEnabled)); } public bool? SelectAllCheckBoxState { get => _selectAllCheckBoxState; set => SetProperty(ref _selectAllCheckBoxState, value, nameof(SelectAllCheckBoxState)); } public bool SelectAllCheckBoxThreeStateEnable { get => _selectAllCheckBoxThreeStateEnable; set => SetProperty(ref _selectAllCheckBoxThreeStateEnable, value, nameof(SelectAllCheckBoxThreeStateEnable)); } public string SelectAllCheckBoxAutomationText => ServicesVSResources.Select_All; public string DestinationTreeViewAutomationText => ServicesVSResources.Select_destination; public string SelectMemberListViewAutomationText => ServicesVSResources.Select_member; private bool _selectAllCheckBoxThreeStateEnable; private bool? _selectAllCheckBoxState; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> _symbolToDependentsMap; private bool _okButtonEnabled; public PullMemberUpDialogViewModel( IUIThreadOperationExecutor uiThreadOperationExecutor, ImmutableArray<MemberSymbolViewModel> members, BaseTypeTreeNodeViewModel destinationTreeViewModel, ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> dependentsMap) { _uiThreadOperationExecutor = uiThreadOperationExecutor; _symbolToDependentsMap = dependentsMap; MemberSelectionViewModel = new MemberSelectionViewModel( _uiThreadOperationExecutor, members, _symbolToDependentsMap); MemberSelectionViewModel.PropertyChanged += (s, e) => { if (e.PropertyName == nameof(MemberSelectionViewModel.CheckedMembers)) { EnableOrDisableOkButton(); } }; DestinationTreeNodeViewModel = destinationTreeViewModel; _selectedDestination = destinationTreeViewModel; EnableOrDisableOkButton(); } public BaseTypeTreeNodeViewModel DestinationTreeNodeViewModel { get; } public MemberSelectionViewModel MemberSelectionViewModel { get; } private BaseTypeTreeNodeViewModel _selectedDestination; public BaseTypeTreeNodeViewModel SelectedDestination { get => _selectedDestination; set { if (SetProperty(ref _selectedDestination, value)) { MemberSelectionViewModel.UpdateMembersBasedOnDestinationKind(_selectedDestination.Symbol.TypeKind); EnableOrDisableOkButton(); } } } public PullMembersUpOptions CreatePullMemberUpOptions() { var selectedOptionFromDialog = MemberSelectionViewModel.GetSelectedMembers(); var options = PullMembersUpOptionsBuilder.BuildPullMembersUpOptions( SelectedDestination.Symbol, selectedOptionFromDialog); return options; } private void EnableOrDisableOkButton() { var selectedMembers = MemberSelectionViewModel.CheckedMembers; OkButtonEnabled = SelectedDestination != DestinationTreeNodeViewModel && selectedMembers.Any(); } } }
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/PullMemberUp/VisualStudioPullMemberUpService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PullMemberUp; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp { [ExportWorkspaceService(typeof(IPullMemberUpOptionsService), ServiceLayer.Host), Shared] internal class VisualStudioPullMemberUpService : IPullMemberUpOptionsService { private readonly IGlyphService _glyphService; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioPullMemberUpService(IGlyphService glyphService, IUIThreadOperationExecutor uiThreadOperationExecutor) { _glyphService = glyphService; _uiThreadOperationExecutor = uiThreadOperationExecutor; } public PullMembersUpOptions GetPullMemberUpOptions(Document document, ImmutableArray<ISymbol> selectedMembers) { // all selected members must have the same containing type var containingType = selectedMembers[0].ContainingType; var membersInType = containingType.GetMembers(). WhereAsArray(MemberAndDestinationValidator.IsMemberValid); var memberViewModels = membersInType .SelectAsArray(member => new PullMemberUpSymbolViewModel(member, _glyphService) { // The member user selected will be checked at the beginning. IsChecked = selectedMembers.Any(SymbolEquivalenceComparer.Instance.Equals, member), MakeAbstract = false, IsMakeAbstractCheckable = !member.IsKind(SymbolKind.Field) && !member.IsAbstract, IsCheckable = true }); using var cancellationTokenSource = new CancellationTokenSource(); var baseTypeRootViewModel = BaseTypeTreeNodeViewModel.CreateBaseTypeTree( _glyphService, document.Project.Solution, containingType, cancellationTokenSource.Token); var memberToDependentsMap = SymbolDependentsBuilder.FindMemberToDependentsMap(membersInType, document.Project, cancellationTokenSource.Token); var viewModel = new PullMemberUpDialogViewModel(_uiThreadOperationExecutor, memberViewModels, baseTypeRootViewModel, memberToDependentsMap); var dialog = new PullMemberUpDialog(viewModel); var result = dialog.ShowModal(); // Dialog has finshed its work, cancel finding dependents task. cancellationTokenSource.Cancel(); if (result.GetValueOrDefault()) { return dialog.ViewModel.CreatePullMemberUpOptions(); } else { 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.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PullMemberUp; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp { [ExportWorkspaceService(typeof(IPullMemberUpOptionsService), ServiceLayer.Host), Shared] internal class VisualStudioPullMemberUpService : IPullMemberUpOptionsService { private readonly IGlyphService _glyphService; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioPullMemberUpService(IGlyphService glyphService, IUIThreadOperationExecutor uiThreadOperationExecutor) { _glyphService = glyphService; _uiThreadOperationExecutor = uiThreadOperationExecutor; } public PullMembersUpOptions GetPullMemberUpOptions(Document document, ImmutableArray<ISymbol> selectedMembers) { // all selected members must have the same containing type var containingType = selectedMembers[0].ContainingType; var membersInType = containingType.GetMembers(). WhereAsArray(MemberAndDestinationValidator.IsMemberValid); var memberViewModels = membersInType .SelectAsArray(member => new MemberSymbolViewModel(member, _glyphService) { // The member user selected will be checked at the beginning. IsChecked = selectedMembers.Any(SymbolEquivalenceComparer.Instance.Equals, member), MakeAbstract = false, IsMakeAbstractCheckable = !member.IsKind(SymbolKind.Field) && !member.IsAbstract, IsCheckable = true }); using var cancellationTokenSource = new CancellationTokenSource(); var baseTypeRootViewModel = BaseTypeTreeNodeViewModel.CreateBaseTypeTree( _glyphService, document.Project.Solution, containingType, cancellationTokenSource.Token); var memberToDependentsMap = SymbolDependentsBuilder.FindMemberToDependentsMap(membersInType, document.Project, cancellationTokenSource.Token); var viewModel = new PullMemberUpDialogViewModel(_uiThreadOperationExecutor, memberViewModels, baseTypeRootViewModel, memberToDependentsMap); var dialog = new PullMemberUpDialog(viewModel); var result = dialog.ShowModal(); // Dialog has finshed its work, cancel finding dependents task. cancellationTokenSource.Cancel(); if (result.GetValueOrDefault()) { return dialog.ViewModel.CreatePullMemberUpOptions(); } else { return null; } } } }
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Test/CommonControls/MemberSelectionViewModelTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PullMemberUp Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CommonControls <[UseExportProvider]> Public Class MemberSelectionViewModelTests <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function SelectPublicMembers() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } public double e => 2.717; public const days = 365; private double pi => 3.1416; protected float goldenRadio = 0.618; internal float gravitational = 6.67e-11; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) viewModel.SelectPublic() For Each member In viewModel.Members.Where(Function(memberViewModel) memberViewModel.Symbol.DeclaredAccessibility = Microsoft.CodeAnalysis.Accessibility.Public) Assert.True(member.IsChecked) Next End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestMemberSelectionViewModelDont_PullDisableItem() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } public double e => 2.717; public const days = 365; private double pi => 3.1416; protected float goldenRadio = 0.618; internal float gravitational = 6.67e-11; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) viewModel.SelectAll() ' select an interface, all checkbox of field will be disable viewModel.UpdateMembersBasedOnDestinationKind(TypeKind.Interface) ' Make sure fields are not pulled to interface Dim checkedMembers = viewModel.CheckedMembers() Assert.Empty(checkedMembers.WhereAsArray(Function(analysisResult) analysisResult.Symbol.IsKind(SymbolKind.Field))) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function SelectDependents() As Task Dim markUp = <Text><![CDATA[ using System; class Level1BaseClass { } class MyClass : Level1BaseClass { private int i = 100; private event EventHandler FooEvent; public void G$$oo() { int i = BarBar(e); What = 1000; } public int BarBar(double e) { Nested1(); return 1000; } private void Nested1() { int i = 1000; gravitational == 1.0; } internal float gravitational = 6.67e-11; private int What {get; set; } public double e => 2.717; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) viewModel.SelectDependents() ' Dependents of Goo Assert.True(FindMemberByName("Goo()", viewModel.Members).IsChecked) Assert.True(FindMemberByName("e", viewModel.Members).IsChecked) Assert.True(FindMemberByName("What", viewModel.Members).IsChecked) Assert.True(FindMemberByName("BarBar(double)", viewModel.Members).IsChecked) Assert.True(FindMemberByName("Nested1()", viewModel.Members).IsChecked) Assert.True(FindMemberByName("gravitational", viewModel.Members).IsChecked) ' Not the depenents of Goo Assert.False(FindMemberByName("i", viewModel.Members).IsChecked) Assert.False(FindMemberByName("FooEvent", viewModel.Members).IsChecked) End Function Private Shared Function FindMemberByName(name As String, memberArray As ImmutableArray(Of PullMemberUpSymbolViewModel)) As PullMemberUpSymbolViewModel Dim member = memberArray.FirstOrDefault(Function(memberViewModel) memberViewModel.SymbolName.Equals(name)) If (member Is Nothing) Then Assert.True(False, $"No member called {name} found") End If Return member End Function Private Shared Async Function GetViewModelAsync(markup As XElement, languageName As String) As Task(Of MemberSelectionViewModel) Dim workspaceXml = <Workspace> <Project Language=<%= languageName %> CommonReferences="true"> <Document><%= markup.Value %></Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(workspaceXml) Dim doc = workspace.Documents.Single() Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id) If (Not doc.CursorPosition.HasValue) Then Throw New ArgumentException("Missing caret location in document.") End If Dim tree = Await workspaceDoc.GetSyntaxTreeAsync() Dim token = Await tree.GetTouchingWordAsync(doc.CursorPosition.Value, workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), CancellationToken.None) Dim memberSymbol = (Await workspaceDoc.GetSemanticModelAsync()).GetDeclaredSymbol(token.Parent) Dim membersInType = memberSymbol.ContainingType.GetMembers().WhereAsArray(Function(member) MemberAndDestinationValidator.IsMemberValid(member)) Dim membersViewModel = membersInType.SelectAsArray( Function(member) New PullMemberUpSymbolViewModel(member, glyphService:=Nothing) With {.IsChecked = member.Equals(memberSymbol), .IsCheckable = True, .MakeAbstract = False}) Dim memberToDependents = SymbolDependentsBuilder.FindMemberToDependentsMap(membersInType, workspaceDoc.Project, CancellationToken.None) Return New MemberSelectionViewModel( workspace.GetService(Of IUIThreadOperationExecutor), membersViewModel, memberToDependents) 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.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PullMemberUp Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp Imports Microsoft.VisualStudio.LanguageServices.Utilities Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CommonControls <[UseExportProvider]> Public Class MemberSelectionViewModelTests <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function SelectPublicMembers() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } public double e => 2.717; public const days = 365; private double pi => 3.1416; protected float goldenRadio = 0.618; internal float gravitational = 6.67e-11; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) viewModel.SelectPublic() For Each member In viewModel.Members.Where(Function(memberViewModel) memberViewModel.Symbol.DeclaredAccessibility = Microsoft.CodeAnalysis.Accessibility.Public) Assert.True(member.IsChecked) Next End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestMemberSelectionViewModelDont_PullDisableItem() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } public double e => 2.717; public const days = 365; private double pi => 3.1416; protected float goldenRadio = 0.618; internal float gravitational = 6.67e-11; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) viewModel.SelectAll() ' select an interface, all checkbox of field will be disable viewModel.UpdateMembersBasedOnDestinationKind(TypeKind.Interface) ' Make sure fields are not pulled to interface Dim checkedMembers = viewModel.CheckedMembers() Assert.Empty(checkedMembers.WhereAsArray(Function(analysisResult) analysisResult.Symbol.IsKind(SymbolKind.Field))) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function SelectDependents() As Task Dim markUp = <Text><![CDATA[ using System; class Level1BaseClass { } class MyClass : Level1BaseClass { private int i = 100; private event EventHandler FooEvent; public void G$$oo() { int i = BarBar(e); What = 1000; } public int BarBar(double e) { Nested1(); return 1000; } private void Nested1() { int i = 1000; gravitational == 1.0; } internal float gravitational = 6.67e-11; private int What {get; set; } public double e => 2.717; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) viewModel.SelectDependents() ' Dependents of Goo Assert.True(FindMemberByName("Goo()", viewModel.Members).IsChecked) Assert.True(FindMemberByName("e", viewModel.Members).IsChecked) Assert.True(FindMemberByName("What", viewModel.Members).IsChecked) Assert.True(FindMemberByName("BarBar(double)", viewModel.Members).IsChecked) Assert.True(FindMemberByName("Nested1()", viewModel.Members).IsChecked) Assert.True(FindMemberByName("gravitational", viewModel.Members).IsChecked) ' Not the depenents of Goo Assert.False(FindMemberByName("i", viewModel.Members).IsChecked) Assert.False(FindMemberByName("FooEvent", viewModel.Members).IsChecked) End Function Private Shared Function FindMemberByName(name As String, memberArray As ImmutableArray(Of MemberSymbolViewModel)) As MemberSymbolViewModel Dim member = memberArray.FirstOrDefault(Function(memberViewModel) memberViewModel.SymbolName.Equals(name)) If (member Is Nothing) Then Assert.True(False, $"No member called {name} found") End If Return member End Function Private Shared Async Function GetViewModelAsync(markup As XElement, languageName As String) As Task(Of MemberSelectionViewModel) Dim workspaceXml = <Workspace> <Project Language=<%= languageName %> CommonReferences="true"> <Document><%= markup.Value %></Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(workspaceXml) Dim doc = workspace.Documents.Single() Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id) If (Not doc.CursorPosition.HasValue) Then Throw New ArgumentException("Missing caret location in document.") End If Dim tree = Await workspaceDoc.GetSyntaxTreeAsync() Dim token = Await tree.GetTouchingWordAsync(doc.CursorPosition.Value, workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), CancellationToken.None) Dim memberSymbol = (Await workspaceDoc.GetSemanticModelAsync()).GetDeclaredSymbol(token.Parent) Dim membersInType = memberSymbol.ContainingType.GetMembers().WhereAsArray(Function(member) MemberAndDestinationValidator.IsMemberValid(member)) Dim membersViewModel = membersInType.SelectAsArray( Function(member) New MemberSymbolViewModel(member, glyphService:=Nothing) With {.IsChecked = member.Equals(memberSymbol), .IsCheckable = True, .MakeAbstract = False}) Dim memberToDependents = SymbolDependentsBuilder.FindMemberToDependentsMap(membersInType, workspaceDoc.Project, CancellationToken.None) Return New MemberSelectionViewModel( workspace.GetService(Of IUIThreadOperationExecutor), membersViewModel, memberToDependents) End Using End Function End Class End Namespace
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Test/ExtractInterface/ExtractInterfaceViewModelTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ExtractInterface <[UseExportProvider]> Public Class ExtractInterfaceViewModelTests <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_MembersCheckedByDefault() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.True(viewModel.MemberContainers.Single().IsChecked) End Function <Fact> <WorkItem(716122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716122"), Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_InterfaceNameIsTrimmedOnSubmit() As Task Dim markup = <Text><![CDATA[ public class C$$ { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IC") viewModel.DestinationViewModel.TypeName = " IC2 " Dim submitSucceeded = viewModel.TrySubmit() Assert.True(submitSucceeded, String.Format("Submit failed unexpectedly.")) End Function <Fact> <WorkItem(716122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716122"), Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_FileNameIsTrimmedOnSubmit() As Task Dim markup = <Text><![CDATA[ public class C$$ { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IC") viewModel.DestinationViewModel.FileName = " IC2.cs " Dim submitSucceeded = viewModel.TrySubmit() Assert.True(submitSucceeded, String.Format("Submit failed unexpectedly.")) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_SuccessfulCommit() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Dim submitSucceeded = viewModel.TrySubmit() Assert.True(submitSucceeded, String.Format("Submit failed unexpectedly.")) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_SuccessfulCommit_NonemptyStrictSubsetOfMembersSelected() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } public void Bar() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") viewModel.MemberContainers.First().IsChecked = False Dim submitSucceeded = viewModel.TrySubmit() Assert.True(submitSucceeded, String.Format("Submit failed unexpectedly.")) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_FailedCommit_InterfaceNameConflict() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass", conflictingTypeNames:=New List(Of String) From {"IMyClass"}) Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_FailedCommit_InterfaceNameNotAnIdentifier() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") viewModel.DestinationViewModel.TypeName = "SomeNamespace.IMyClass" Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_FailedCommit_BadFileExtension() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") viewModel.DestinationViewModel.FileName = "FileName.vb" Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_FailedCommit_BadFileName() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") viewModel.DestinationViewModel.FileName = "Bad*FileName.cs" Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_FailedCommit_BadFileName2() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") viewModel.DestinationViewModel.FileName = "?BadFileName.cs" Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_FailedCommit_NoMembersSelected() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") viewModel.MemberContainers.Single().IsChecked = False Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_MemberDisplay_Method() As Task Dim markup = <Text><![CDATA[ using System; class $$MyClass { public void Goo<T>(T t, System.Diagnostics.CorrelationManager v, ref int w, Nullable<System.Int32> x = 7, string y = "hi", params int[] z) { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("Goo<T>(T, CorrelationManager, ref int, [int?], [string], params int[])", viewModel.MemberContainers.Single().SymbolName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_MemberDisplay_Property() As Task Dim markup = <Text><![CDATA[ using System; class $$MyClass { public int Goo { get { return 5; } set { } } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("Goo", viewModel.MemberContainers.Where(Function(c) c.Symbol.IsKind(SymbolKind.Property)).Single().SymbolName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_MemberDisplay_Indexer() As Task Dim markup = <Text><![CDATA[ using System; class $$MyClass { public int this[Nullable<Int32> x, string y = "hi"] { get { return 1; } set { } } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("this[int?, [string]]", viewModel.MemberContainers.Where(Function(c) c.Symbol.IsKind(SymbolKind.Property)).Single().SymbolName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> <WorkItem(37176, "https://github.com/dotnet/roslyn/issues/37176")> Public Async Function TestExtractInterface_MemberDisplay_NullableReferenceType() As Task Dim markup = <Text><![CDATA[ #nullable enable using System.Collections.Generic; class $$MyClass { public void M(string? s, IEnumerable<string?> e) { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("M(string?, IEnumerable<string?>)", viewModel.MemberContainers.Single(Function(c) c.Symbol.IsKind(SymbolKind.Method)).SymbolName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_MembersSorted() As Task Dim markup = <Text><![CDATA[ public class $$MyClass { public void Goo(string s) { } public void Goo(int i) { } public void Goo(int i, string s) { } public void Goo() { } public void Goo(int i, int i2) { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal(5, viewModel.MemberContainers.Count) Assert.Equal("Goo()", viewModel.MemberContainers.ElementAt(0).SymbolName) Assert.Equal("Goo(int)", viewModel.MemberContainers.ElementAt(1).SymbolName) Assert.Equal("Goo(int, int)", viewModel.MemberContainers.ElementAt(2).SymbolName) Assert.Equal("Goo(int, string)", viewModel.MemberContainers.ElementAt(3).SymbolName) Assert.Equal("Goo(string)", viewModel.MemberContainers.ElementAt(4).SymbolName) End Function Private Shared Async Function GetViewModelAsync(markup As XElement, languageName As String, defaultInterfaceName As String, Optional defaultNamespace As String = "", Optional generatedNameTypeParameterSuffix As String = "", Optional conflictingTypeNames As List(Of String) = Nothing, Optional isValidIdentifier As Boolean = True) As Tasks.Task(Of ExtractInterfaceDialogViewModel) Dim workspaceXml = <Workspace> <Project Language=<%= languageName %> CommonReferences="true"> <Document><%= markup.NormalizedValue.Replace(vbCrLf, vbLf) %></Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(workspaceXml) Dim doc = workspace.Documents.Single() Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id) If (Not doc.CursorPosition.HasValue) Then Assert.True(False, "Missing caret location in document.") End If Dim tree = Await workspaceDoc.GetSyntaxTreeAsync() Dim token = Await tree.GetTouchingWordAsync(doc.CursorPosition.Value, workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), CancellationToken.None) Dim symbol = (Await workspaceDoc.GetSemanticModelAsync()).GetDeclaredSymbol(token.Parent) Dim extractableMembers = DirectCast(symbol, INamedTypeSymbol).GetMembers().Where(Function(s) Not (TypeOf s Is IMethodSymbol) OrElse DirectCast(s, IMethodSymbol).MethodKind <> MethodKind.Constructor) Return New ExtractInterfaceDialogViewModel( workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), glyphService:=Nothing, notificationService:=New TestNotificationService(), defaultInterfaceName:=defaultInterfaceName, extractableMembers:=extractableMembers.ToList(), conflictingTypeNames:=If(conflictingTypeNames, New List(Of String)), defaultNamespace:=defaultNamespace, generatedNameTypeParameterSuffix:=generatedNameTypeParameterSuffix, languageName:=doc.Project.Language) 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 System.Threading.Tasks Imports System.Collections.Immutable Imports System.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface Imports Roslyn.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ExtractInterface <[UseExportProvider]> Public Class ExtractInterfaceViewModelTests <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_MembersCheckedByDefault() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.True(viewModel.MemberContainers.Single().IsChecked) End Function <Fact> <WorkItem(716122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716122"), Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_InterfaceNameIsTrimmedOnSubmit() As Task Dim markup = <Text><![CDATA[ public class C$$ { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IC") viewModel.DestinationViewModel.TypeName = " IC2 " Dim submitSucceeded = viewModel.TrySubmit() Assert.True(submitSucceeded, String.Format("Submit failed unexpectedly.")) End Function <Fact> <WorkItem(716122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716122"), Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_FileNameIsTrimmedOnSubmit() As Task Dim markup = <Text><![CDATA[ public class C$$ { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IC") viewModel.DestinationViewModel.FileName = " IC2.cs " Dim submitSucceeded = viewModel.TrySubmit() Assert.True(submitSucceeded, String.Format("Submit failed unexpectedly.")) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_SuccessfulCommit() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Dim submitSucceeded = viewModel.TrySubmit() Assert.True(submitSucceeded, String.Format("Submit failed unexpectedly.")) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_SuccessfulCommit_NonemptyStrictSubsetOfMembersSelected() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } public void Bar() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") viewModel.MemberContainers.First().IsChecked = False Dim submitSucceeded = viewModel.TrySubmit() Assert.True(submitSucceeded, String.Format("Submit failed unexpectedly.")) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_FailedCommit_InterfaceNameConflict() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass", conflictingTypeNames:=New List(Of String) From {"IMyClass"}) Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_FailedCommit_InterfaceNameNotAnIdentifier() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") viewModel.DestinationViewModel.TypeName = "SomeNamespace.IMyClass" Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_FailedCommit_BadFileExtension() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") viewModel.DestinationViewModel.FileName = "FileName.vb" Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_FailedCommit_BadFileName() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") viewModel.DestinationViewModel.FileName = "Bad*FileName.cs" Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_FailedCommit_BadFileName2() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") viewModel.DestinationViewModel.FileName = "?BadFileName.cs" Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_FailedCommit_NoMembersSelected() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") viewModel.MemberContainers.Single().IsChecked = False Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_MemberDisplay_Method() As Task Dim markup = <Text><![CDATA[ using System; class $$MyClass { public void Goo<T>(T t, System.Diagnostics.CorrelationManager v, ref int w, Nullable<System.Int32> x = 7, string y = "hi", params int[] z) { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("Goo<T>(T, CorrelationManager, ref int, [int?], [string], params int[])", viewModel.MemberContainers.Single().SymbolName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_MemberDisplay_Property() As Task Dim markup = <Text><![CDATA[ using System; class $$MyClass { public int Goo { get { return 5; } set { } } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("Goo", viewModel.MemberContainers.Where(Function(c) c.Symbol.IsKind(SymbolKind.Property)).Single().SymbolName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_MemberDisplay_Indexer() As Task Dim markup = <Text><![CDATA[ using System; class $$MyClass { public int this[Nullable<Int32> x, string y = "hi"] { get { return 1; } set { } } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("this[int?, [string]]", viewModel.MemberContainers.Where(Function(c) c.Symbol.IsKind(SymbolKind.Property)).Single().SymbolName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> <WorkItem(37176, "https://github.com/dotnet/roslyn/issues/37176")> Public Async Function TestExtractInterface_MemberDisplay_NullableReferenceType() As Task Dim markup = <Text><![CDATA[ #nullable enable using System.Collections.Generic; class $$MyClass { public void M(string? s, IEnumerable<string?> e) { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("M(string?, IEnumerable<string?>)", viewModel.MemberContainers.Single(Function(c) c.Symbol.IsKind(SymbolKind.Method)).SymbolName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TestExtractInterface_MembersSorted() As Task Dim markup = <Text><![CDATA[ public class $$MyClass { public void Goo(string s) { } public void Goo(int i) { } public void Goo(int i, string s) { } public void Goo() { } public void Goo(int i, int i2) { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal(5, viewModel.MemberContainers.Count) Assert.Equal("Goo()", viewModel.MemberContainers.ElementAt(0).SymbolName) Assert.Equal("Goo(int)", viewModel.MemberContainers.ElementAt(1).SymbolName) Assert.Equal("Goo(int, int)", viewModel.MemberContainers.ElementAt(2).SymbolName) Assert.Equal("Goo(int, string)", viewModel.MemberContainers.ElementAt(3).SymbolName) Assert.Equal("Goo(string)", viewModel.MemberContainers.ElementAt(4).SymbolName) End Function Private Shared Async Function GetViewModelAsync(markup As XElement, languageName As String, defaultInterfaceName As String, Optional defaultNamespace As String = "", Optional generatedNameTypeParameterSuffix As String = "", Optional conflictingTypeNames As List(Of String) = Nothing, Optional isValidIdentifier As Boolean = True) As Tasks.Task(Of ExtractInterfaceDialogViewModel) Dim workspaceXml = <Workspace> <Project Language=<%= languageName %> CommonReferences="true"> <Document><%= markup.NormalizedValue.Replace(vbCrLf, vbLf) %></Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(workspaceXml) Dim doc = workspace.Documents.Single() Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id) If (Not doc.CursorPosition.HasValue) Then Assert.True(False, "Missing caret location in document.") End If Dim tree = Await workspaceDoc.GetSyntaxTreeAsync() Dim token = Await tree.GetTouchingWordAsync(doc.CursorPosition.Value, workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), CancellationToken.None) Dim symbol = (Await workspaceDoc.GetSemanticModelAsync()).GetDeclaredSymbol(token.Parent) Dim extractableMembers = DirectCast(symbol, INamedTypeSymbol).GetMembers().Where(Function(s) Not (TypeOf s Is IMethodSymbol) OrElse DirectCast(s, IMethodSymbol).MethodKind <> MethodKind.Constructor) Dim memberViewModels = extractableMembers.Select(Function(member As ISymbol) Return New MemberSymbolViewModel(member, Nothing) End Function) Return New ExtractInterfaceDialogViewModel( workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), notificationService:=New TestNotificationService(), uiThreadOperationExecutor:=Nothing, defaultInterfaceName:=defaultInterfaceName, conflictingTypeNames:=If(conflictingTypeNames, New List(Of String)), memberViewModels:=memberViewModels.ToImmutableArray(), defaultNamespace:=defaultNamespace, generatedNameTypeParameterSuffix:=generatedNameTypeParameterSuffix, languageName:=doc.Project.Language) End Using End Function End Class End Namespace
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Test/PullMemberUp/PullMemberUpViewModelTest.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PullMemberUp Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.PullMemberUp <[UseExportProvider]> Public Class PullMemberUpViewModelTest <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_VerifySameBaseTypeAppearMultipleTimes() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes Assert.Equal("Level1BaseClass", baseTypeTree(0).SymbolName) Assert.Equal("Level1Interface", baseTypeTree(1).SymbolName) Assert.Equal("Level2Interface", baseTypeTree(0).BaseTypeNodes(0).SymbolName) Assert.Equal("Level2Interface", baseTypeTree(1).BaseTypeNodes(0).SymbolName) Assert.Empty(baseTypeTree(0).BaseTypeNodes(0).BaseTypeNodes) Assert.Empty(baseTypeTree(1).BaseTypeNodes(0).BaseTypeNodes) Assert.False(viewModel.OkButtonEnabled) viewModel.SelectedDestination = baseTypeTree(0) Assert.True(viewModel.OkButtonEnabled) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_NoVBDestinationAppearInCSharpProject() As Task Dim markUp = <Text><![CDATA[ <Workspace> <Project Language="C#" AssemblyName="CSAssembly" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public interface ITestInterface { } public class TestClass : VBClass, ITestInterface { public int Bar$$bar() { return 12345; } } </Document> </Project> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes ' C# types will be showed Assert.Equal("ITestInterface", baseTypeTree(0).SymbolName) ' Make sure Visual basic types are not showed since we are not ready to support cross language scenario Assert.Single(baseTypeTree) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_SelectInterfaceDisableMakeAbstractCheckbox() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } public double e => 2.717; public const days = 365; private double pi => 3.1416; protected float goldenRadio = 0.618; internal float gravitational = 6.67e-11; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes Assert.Equal("Level1Interface", baseTypeTree(1).SymbolName) viewModel.SelectedDestination = baseTypeTree(1) For Each member In viewModel.MemberSelectionViewModel.Members.WhereAsArray( Function(memberViewModel) Return Not memberViewModel.Symbol.IsKind(SymbolKind.Field) And Not memberViewModel.Symbol.IsAbstract End Function) Assert.False(member.IsMakeAbstractCheckable) Next End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_SelectInterfaceDisableFieldCheckbox() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } public double e => 2.717; public const days = 365; private double pi => 3.1416; protected float goldenRadio = 0.618; internal float gravitational = 6.67e-11; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes Assert.Equal("Level1Interface", baseTypeTree(1).SymbolName) viewModel.SelectedDestination = baseTypeTree(1) For Each member In viewModel.MemberSelectionViewModel.Members.Where(Function(memberViewModel) memberViewModel.Symbol.IsKind(SymbolKind.Field)) Assert.False(member.IsCheckable) Assert.False(String.IsNullOrEmpty(member.TooltipText)) Next End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_SelectClassEnableFieldCheckbox() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } public double e => 2.717; public const days = 365; private double pi => 3.1416; protected float goldenRadio = 0.618; internal float gravitational = 6.67e-11; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes ' First select an interface, all checkbox will be disable as the previous test. Assert.Equal("Level1Interface", baseTypeTree(1).SymbolName) viewModel.SelectedDestination = baseTypeTree(1) ' Second select a class, check all checkboxs will be resumed. Assert.Equal("Level1BaseClass", baseTypeTree(0).SymbolName) viewModel.SelectedDestination = baseTypeTree(0) For Each member In viewModel.MemberSelectionViewModel.Members.Where(Function(memberViewModel) memberViewModel.Symbol.IsKind(SymbolKind.Field)) Assert.True(member.IsCheckable) Assert.True(String.IsNullOrEmpty(member.TooltipText)) Next End Function Private Shared Function FindMemberByName(name As String, memberArray As ImmutableArray(Of PullMemberUpSymbolViewModel)) As PullMemberUpSymbolViewModel Dim member = memberArray.FirstOrDefault(Function(memberViewModel) memberViewModel.SymbolName.Equals(name)) If (member Is Nothing) Then Assert.True(False, $"No member called {name} found") End If Return member End Function Private Shared Async Function GetViewModelAsync(markup As XElement, languageName As String) As Task(Of PullMemberUpDialogViewModel) Dim workspaceXml = <Workspace> <Project Language=<%= languageName %> CommonReferences="true"> <Document><%= markup.Value %></Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(workspaceXml) Dim doc = workspace.Documents.Single() Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id) If (Not doc.CursorPosition.HasValue) Then Throw New ArgumentException("Missing caret location in document.") End If Dim tree = Await workspaceDoc.GetSyntaxTreeAsync() Dim token = Await tree.GetTouchingWordAsync(doc.CursorPosition.Value, workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), CancellationToken.None) Dim memberSymbol = (Await workspaceDoc.GetSemanticModelAsync()).GetDeclaredSymbol(token.Parent) Dim baseTypeTree = BaseTypeTreeNodeViewModel.CreateBaseTypeTree(glyphService:=Nothing, workspaceDoc.Project.Solution, memberSymbol.ContainingType, CancellationToken.None) Dim membersInType = memberSymbol.ContainingType.GetMembers().WhereAsArray(Function(member) MemberAndDestinationValidator.IsMemberValid(member)) Dim membersViewModel = membersInType.SelectAsArray( Function(member) New PullMemberUpSymbolViewModel(member, glyphService:=Nothing) With {.IsChecked = member.Equals(memberSymbol), .IsCheckable = True, .MakeAbstract = False}) Dim memberToDependents = SymbolDependentsBuilder.FindMemberToDependentsMap(membersInType, workspaceDoc.Project, CancellationToken.None) Return New PullMemberUpDialogViewModel( workspace.GetService(Of IUIThreadOperationExecutor), membersViewModel, baseTypeTree, memberToDependents) 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.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PullMemberUp Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog Imports Microsoft.VisualStudio.LanguageServices.Utilities Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.PullMemberUp <[UseExportProvider]> Public Class PullMemberUpViewModelTest <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_VerifySameBaseTypeAppearMultipleTimes() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes Assert.Equal("Level1BaseClass", baseTypeTree(0).SymbolName) Assert.Equal("Level1Interface", baseTypeTree(1).SymbolName) Assert.Equal("Level2Interface", baseTypeTree(0).BaseTypeNodes(0).SymbolName) Assert.Equal("Level2Interface", baseTypeTree(1).BaseTypeNodes(0).SymbolName) Assert.Empty(baseTypeTree(0).BaseTypeNodes(0).BaseTypeNodes) Assert.Empty(baseTypeTree(1).BaseTypeNodes(0).BaseTypeNodes) Assert.False(viewModel.OkButtonEnabled) viewModel.SelectedDestination = baseTypeTree(0) Assert.True(viewModel.OkButtonEnabled) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_NoVBDestinationAppearInCSharpProject() As Task Dim markUp = <Text><![CDATA[ <Workspace> <Project Language="C#" AssemblyName="CSAssembly" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public interface ITestInterface { } public class TestClass : VBClass, ITestInterface { public int Bar$$bar() { return 12345; } } </Document> </Project> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes ' C# types will be showed Assert.Equal("ITestInterface", baseTypeTree(0).SymbolName) ' Make sure Visual basic types are not showed since we are not ready to support cross language scenario Assert.Single(baseTypeTree) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_SelectInterfaceDisableMakeAbstractCheckbox() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } public double e => 2.717; public const days = 365; private double pi => 3.1416; protected float goldenRadio = 0.618; internal float gravitational = 6.67e-11; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes Assert.Equal("Level1Interface", baseTypeTree(1).SymbolName) viewModel.SelectedDestination = baseTypeTree(1) For Each member In viewModel.MemberSelectionViewModel.Members.WhereAsArray( Function(memberViewModel) Return Not memberViewModel.Symbol.IsKind(SymbolKind.Field) And Not memberViewModel.Symbol.IsAbstract End Function) Assert.False(member.IsMakeAbstractCheckable) Next End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_SelectInterfaceDisableFieldCheckbox() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } public double e => 2.717; public const days = 365; private double pi => 3.1416; protected float goldenRadio = 0.618; internal float gravitational = 6.67e-11; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes Assert.Equal("Level1Interface", baseTypeTree(1).SymbolName) viewModel.SelectedDestination = baseTypeTree(1) For Each member In viewModel.MemberSelectionViewModel.Members.Where(Function(memberViewModel) memberViewModel.Symbol.IsKind(SymbolKind.Field)) Assert.False(member.IsCheckable) Assert.False(String.IsNullOrEmpty(member.TooltipText)) Next End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_SelectClassEnableFieldCheckbox() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } public double e => 2.717; public const days = 365; private double pi => 3.1416; protected float goldenRadio = 0.618; internal float gravitational = 6.67e-11; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes ' First select an interface, all checkbox will be disable as the previous test. Assert.Equal("Level1Interface", baseTypeTree(1).SymbolName) viewModel.SelectedDestination = baseTypeTree(1) ' Second select a class, check all checkboxs will be resumed. Assert.Equal("Level1BaseClass", baseTypeTree(0).SymbolName) viewModel.SelectedDestination = baseTypeTree(0) For Each member In viewModel.MemberSelectionViewModel.Members.Where(Function(memberViewModel) memberViewModel.Symbol.IsKind(SymbolKind.Field)) Assert.True(member.IsCheckable) Assert.True(String.IsNullOrEmpty(member.TooltipText)) Next End Function Private Shared Function FindMemberByName(name As String, memberArray As ImmutableArray(Of MemberSymbolViewModel)) As MemberSymbolViewModel Dim member = memberArray.FirstOrDefault(Function(memberViewModel) memberViewModel.SymbolName.Equals(name)) If (member Is Nothing) Then Assert.True(False, $"No member called {name} found") End If Return member End Function Private Shared Async Function GetViewModelAsync(markup As XElement, languageName As String) As Task(Of PullMemberUpDialogViewModel) Dim workspaceXml = <Workspace> <Project Language=<%= languageName %> CommonReferences="true"> <Document><%= markup.Value %></Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(workspaceXml) Dim doc = workspace.Documents.Single() Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id) If (Not doc.CursorPosition.HasValue) Then Throw New ArgumentException("Missing caret location in document.") End If Dim tree = Await workspaceDoc.GetSyntaxTreeAsync() Dim token = Await tree.GetTouchingWordAsync(doc.CursorPosition.Value, workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), CancellationToken.None) Dim memberSymbol = (Await workspaceDoc.GetSemanticModelAsync()).GetDeclaredSymbol(token.Parent) Dim baseTypeTree = BaseTypeTreeNodeViewModel.CreateBaseTypeTree(glyphService:=Nothing, workspaceDoc.Project.Solution, memberSymbol.ContainingType, CancellationToken.None) Dim membersInType = memberSymbol.ContainingType.GetMembers().WhereAsArray(Function(member) MemberAndDestinationValidator.IsMemberValid(member)) Dim membersViewModel = membersInType.SelectAsArray( Function(member) New MemberSymbolViewModel(member, glyphService:=Nothing) With {.IsChecked = member.Equals(memberSymbol), .IsCheckable = True, .MakeAbstract = False}) Dim memberToDependents = SymbolDependentsBuilder.FindMemberToDependentsMap(membersInType, workspaceDoc.Project, CancellationToken.None) Return New PullMemberUpDialogViewModel( workspace.GetService(Of IUIThreadOperationExecutor), membersViewModel, baseTypeTree, memberToDependents) End Using End Function End Class End Namespace
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/ExtractInterfaceDialog_InProc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class ExtractInterfaceDialog_InProc : AbstractCodeRefactorDialog_InProc<ExtractInterfaceDialog, ExtractInterfaceDialog.TestAccessor> { private ExtractInterfaceDialog_InProc() { } public static ExtractInterfaceDialog_InProc Create() => new ExtractInterfaceDialog_InProc(); public override void VerifyOpen() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { // Thread.Yield is insufficient; something in the light bulb must be relying on a UI thread // message at lower priority than the Background priority used in testing. WaitForApplicationIdle(Helper.HangMitigatingTimeout); continue; } WaitForApplicationIdle(Helper.HangMitigatingTimeout); return; } } } public bool CloseWindow() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { if (JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationTokenSource.Token)) is null) { return false; } } ClickCancel(); return true; } public void ClickOK() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.OKButton, cancellationTokenSource.Token)); } } public void ClickCancel() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.CancelButton, cancellationTokenSource.Token)); } } public void ClickSelectAll() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.SelectAllButton, cancellationTokenSource.Token)); } } public void ClickDeselectAll() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.DeselectAllButton, cancellationTokenSource.Token)); } } public void SelectSameFile() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.DestinationCurrentFileSelectionRadioButton, cancellationTokenSource.Token)); } } public string GetTargetFileName() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { return JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); return dialog.DestinationControl.fileNameTextBox.Text; }); } } public string[] GetSelectedItems() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { return JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); var memberSelectionList = dialog.GetTestAccessor().Members; var comListItems = memberSelectionList.Items; var listItems = Enumerable.Range(0, comListItems.Count).Select(comListItems.GetItemAt); return listItems.Cast<ExtractInterfaceDialogViewModel.MemberSymbolViewModel>() .Where(viewModel => viewModel.IsChecked) .Select(viewModel => viewModel.SymbolName) .ToArray(); }); } } public void ToggleItem(string item) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); var memberSelectionList = dialog.GetTestAccessor().Members; var items = memberSelectionList.Items.Cast<ExtractInterfaceDialogViewModel.MemberSymbolViewModel>().ToArray(); var itemViewModel = items.Single(x => x.SymbolName == item); itemViewModel.IsChecked = !itemViewModel.IsChecked; // Wait for changes to propagate await Task.Yield(); }); } } protected override ExtractInterfaceDialog.TestAccessor GetAccessor(ExtractInterfaceDialog dialog) => dialog.GetTestAccessor(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.LanguageServices.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class ExtractInterfaceDialog_InProc : AbstractCodeRefactorDialog_InProc<ExtractInterfaceDialog, ExtractInterfaceDialog.TestAccessor> { private ExtractInterfaceDialog_InProc() { } public static ExtractInterfaceDialog_InProc Create() => new ExtractInterfaceDialog_InProc(); public override void VerifyOpen() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { // Thread.Yield is insufficient; something in the light bulb must be relying on a UI thread // message at lower priority than the Background priority used in testing. WaitForApplicationIdle(Helper.HangMitigatingTimeout); continue; } WaitForApplicationIdle(Helper.HangMitigatingTimeout); return; } } } public bool CloseWindow() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { if (JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationTokenSource.Token)) is null) { return false; } } ClickCancel(); return true; } public void ClickOK() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.OKButton, cancellationTokenSource.Token)); } } public void ClickCancel() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.CancelButton, cancellationTokenSource.Token)); } } public void ClickSelectAll() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.SelectAllButton, cancellationTokenSource.Token)); } } public void ClickDeselectAll() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.DeselectAllButton, cancellationTokenSource.Token)); } } public void SelectSameFile() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.DestinationCurrentFileSelectionRadioButton, cancellationTokenSource.Token)); } } public string GetTargetFileName() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { return JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); return dialog.DestinationControl.fileNameTextBox.Text; }); } } public string[] GetSelectedItems() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { return JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); var memberSelectionList = dialog.GetTestAccessor().Members; var comListItems = memberSelectionList.Items; var listItems = Enumerable.Range(0, comListItems.Count).Select(comListItems.GetItemAt); return listItems.Cast<SymbolViewModel<ISymbol>>() .Where(viewModel => viewModel.IsChecked) .Select(viewModel => viewModel.SymbolName) .ToArray(); }); } } public void ToggleItem(string item) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); var memberSelectionList = dialog.GetTestAccessor().Members; var items = memberSelectionList.Items.Cast<MemberSymbolViewModel>().ToArray(); var itemViewModel = items.Single(x => x.SymbolName == item); itemViewModel.IsChecked = !itemViewModel.IsChecked; // Wait for changes to propagate await Task.Yield(); }); } } protected override ExtractInterfaceDialog.TestAccessor GetAccessor(ExtractInterfaceDialog dialog) => dialog.GetTestAccessor(); } }
1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeImplementsStatement.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeElement2))] public sealed class CodeImplementsStatement : AbstractCodeElement { internal static EnvDTE80.CodeElement2 Create( CodeModelState state, AbstractCodeMember parent, string namespaceName, int ordinal) { var element = new CodeImplementsStatement(state, parent, namespaceName, ordinal); var result = (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element); return result; } internal static EnvDTE80.CodeElement2 CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeImplementsStatement(state, fileCodeModel, nodeKind, name); return (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element); } private readonly ParentHandle<AbstractCodeMember> _parentHandle; private readonly string _namespaceName; private readonly int _ordinal; private CodeImplementsStatement( CodeModelState state, AbstractCodeMember parent, string namespaceName, int ordinal) : base(state, parent.FileCodeModel) { _parentHandle = new ParentHandle<AbstractCodeMember>(parent); _namespaceName = namespaceName; _ordinal = ordinal; } private CodeImplementsStatement( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind) { _namespaceName = name; } internal override bool TryLookupNode(out SyntaxNode node) { node = null; var parentNode = _parentHandle.Value.LookupNode(); if (parentNode == null) { return false; } if (!CodeModelService.TryGetImplementsNode(parentNode, _namespaceName, _ordinal, out var implementsNode)) { return false; } node = implementsNode; return node != null; } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementImplementsStmt; } } public override object Parent { get { return _parentHandle.Value; } } public override EnvDTE.CodeElements Children { get { return EmptyCollection.Create(this.State, this); } } protected override void SetName(string value) => throw Exceptions.ThrowENotImpl(); public override void RenameSymbol(string newName) => throw Exceptions.ThrowENotImpl(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeElement2))] public sealed class CodeImplementsStatement : AbstractCodeElement { internal static EnvDTE80.CodeElement2 Create( CodeModelState state, AbstractCodeMember parent, string namespaceName, int ordinal) { var element = new CodeImplementsStatement(state, parent, namespaceName, ordinal); var result = (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element); return result; } internal static EnvDTE80.CodeElement2 CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeImplementsStatement(state, fileCodeModel, nodeKind, name); return (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element); } private readonly ParentHandle<AbstractCodeMember> _parentHandle; private readonly string _namespaceName; private readonly int _ordinal; private CodeImplementsStatement( CodeModelState state, AbstractCodeMember parent, string namespaceName, int ordinal) : base(state, parent.FileCodeModel) { _parentHandle = new ParentHandle<AbstractCodeMember>(parent); _namespaceName = namespaceName; _ordinal = ordinal; } private CodeImplementsStatement( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind) { _namespaceName = name; } internal override bool TryLookupNode(out SyntaxNode node) { node = null; var parentNode = _parentHandle.Value.LookupNode(); if (parentNode == null) { return false; } if (!CodeModelService.TryGetImplementsNode(parentNode, _namespaceName, _ordinal, out var implementsNode)) { return false; } node = implementsNode; return node != null; } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementImplementsStmt; } } public override object Parent { get { return _parentHandle.Value; } } public override EnvDTE.CodeElements Children { get { return EmptyCollection.Create(this.State, this); } } protected override void SetName(string value) => throw Exceptions.ThrowENotImpl(); public override void RenameSymbol(string newName) => throw Exceptions.ThrowENotImpl(); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/PEWriter/Expressions.cs
// Licensed to the .NET Foundation under one or more 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.Cci { /// <summary> /// An expression that can be represented directly in metadata. /// </summary> internal interface IMetadataExpression { /// <summary> /// Calls the visitor.Visit(T) method where T is the most derived object model node interface type implemented by the concrete type /// of the object implementing IStatement. The dispatch method does not invoke Dispatch on any child objects. If child traversal /// is desired, the implementations of the Visit methods should do the subsequent dispatching. /// </summary> void Dispatch(MetadataVisitor visitor); /// <summary> /// The type of value the expression represents. /// </summary> ITypeReference Type { get; } } /// <summary> /// An expression that represents a (name, value) pair and that is typically used in method calls, custom attributes and object initializers. /// </summary> internal interface IMetadataNamedArgument : IMetadataExpression { /// <summary> /// The name of the parameter or property or field that corresponds to the argument. /// </summary> string ArgumentName { get; } /// <summary> /// The value of the argument. /// </summary> IMetadataExpression ArgumentValue { get; } /// <summary> /// True if the named argument provides the value of a field. /// </summary> bool IsField { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Cci { /// <summary> /// An expression that can be represented directly in metadata. /// </summary> internal interface IMetadataExpression { /// <summary> /// Calls the visitor.Visit(T) method where T is the most derived object model node interface type implemented by the concrete type /// of the object implementing IStatement. The dispatch method does not invoke Dispatch on any child objects. If child traversal /// is desired, the implementations of the Visit methods should do the subsequent dispatching. /// </summary> void Dispatch(MetadataVisitor visitor); /// <summary> /// The type of value the expression represents. /// </summary> ITypeReference Type { get; } } /// <summary> /// An expression that represents a (name, value) pair and that is typically used in method calls, custom attributes and object initializers. /// </summary> internal interface IMetadataNamedArgument : IMetadataExpression { /// <summary> /// The name of the parameter or property or field that corresponds to the argument. /// </summary> string ArgumentName { get; } /// <summary> /// The value of the argument. /// </summary> IMetadataExpression ArgumentValue { get; } /// <summary> /// True if the named argument provides the value of a field. /// </summary> bool IsField { get; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/Core/Portable/Options/OptionsHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.CodeStyle; namespace Microsoft.CodeAnalysis.Options { internal static class OptionsHelpers { public static T GetOption<T>(Option<T> option, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option), getOption); public static T GetOption<T>(Option2<T> option, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option), getOption); public static T GetOption<T>(PerLanguageOption<T> option, string? language, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option, language), getOption); public static T GetOption<T>(PerLanguageOption2<T> option, string? language, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option, language), getOption); public static T GetOption<T>(OptionKey2 optionKey, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(optionKey.Option, optionKey.Language), getOption); public static T GetOption<T>(OptionKey optionKey, Func<OptionKey, object?> getOption) { var value = getOption(optionKey); if (value is ICodeStyleOption codeStyleOption) { return (T)codeStyleOption.AsCodeStyleOption<T>(); } return (T)value!; } public static object? GetPublicOption(OptionKey optionKey, Func<OptionKey, object?> getOption) { var value = getOption(optionKey); if (value is ICodeStyleOption codeStyleOption) { return codeStyleOption.AsPublicCodeStyleOption(); } return value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.CodeStyle; namespace Microsoft.CodeAnalysis.Options { internal static class OptionsHelpers { public static T GetOption<T>(Option<T> option, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option), getOption); public static T GetOption<T>(Option2<T> option, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option), getOption); public static T GetOption<T>(PerLanguageOption<T> option, string? language, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option, language), getOption); public static T GetOption<T>(PerLanguageOption2<T> option, string? language, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option, language), getOption); public static T GetOption<T>(OptionKey2 optionKey, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(optionKey.Option, optionKey.Language), getOption); public static T GetOption<T>(OptionKey optionKey, Func<OptionKey, object?> getOption) { var value = getOption(optionKey); if (value is ICodeStyleOption codeStyleOption) { return (T)codeStyleOption.AsCodeStyleOption<T>(); } return (T)value!; } public static object? GetPublicOption(OptionKey optionKey, Func<OptionKey, object?> getOption) { var value = getOption(optionKey); if (value is ICodeStyleOption codeStyleOption) { return codeStyleOption.AsPublicCodeStyleOption(); } return value; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Analyzers/VisualBasic/Tests/UseCoalesceExpression/UseCoalesceExpressionForNullableTests.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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.UseCoalesceExpression Imports Microsoft.CodeAnalysis.VisualBasic.UseCoalesceExpression Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.UseCoalesceExpression Public Class UseCoalesceExpressionForNullableTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicUseCoalesceExpressionForNullableDiagnosticAnalyzer(), New UseCoalesceExpressionForNullableCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)> Public Async Function TestOnLeft_Equals() As Task Await TestInRegularAndScriptAsync( " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = [||]If (Not x.HasValue, y, x.Value) End Sub End Class", " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = If(x, y) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)> Public Async Function TestOnLeft_NotEquals() As Task Await TestInRegularAndScriptAsync( " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = [||]If(x.HasValue, x.Value, y) End Sub End Class", " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = If(x, y) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)> Public Async Function TestComplexExpression() As Task Await TestInRegularAndScriptAsync( " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = [||]If (Not (x + y).HasValue, y, (x + y).Value) End Sub End Class", " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = If((x + y), y) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)> Public Async Function TestParens1() As Task Await TestInRegularAndScriptAsync( " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = [||]If ((Not x.HasValue), y, x.Value) End Sub End Class", " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = If(x, y) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)> Public Async Function TestFixAll1() As Task Await TestInRegularAndScriptAsync( " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z1 = {|FixAllInDocument:If|} (Not x.HasValue, y, x.Value) Dim z2 = If(x.HasValue, x.Value, y) End Sub End Class", " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z1 = If(x, y) Dim z2 = If(x, y) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)> Public Async Function TestFixAll2() As Task Await TestInRegularAndScriptAsync( " Imports System Class C Sub M(x as Integer?, y as Integer?, z as Integer?) dim w = {|FixAllInDocument:If|} (x.HasValue, x.Value, If(y.HasValue, y.Value, z)) End Sub End Class", " Imports System Class C Sub M(x as Integer?, y as Integer?, z as Integer?) dim w = If(x, If(y, z)) End Sub End Class") End Function <WorkItem(17028, "https://github.com/dotnet/roslyn/issues/17028")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)> Public Async Function TestInExpressionOfT() As Task Await TestInRegularAndScriptAsync( " Imports System Imports System.Linq.Expressions Class C Sub M(x as integer?, y as integer) dim e as Expression(of Func(of integer)) = function() [||]If (x.HasValue, x.Value, y) End Sub End Class", " Imports System Imports System.Linq.Expressions Class C Sub M(x as integer?, y as integer) dim e as Expression(of Func(of integer)) = function() {|Warning:If(x, y)|} End Sub End Class") 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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.UseCoalesceExpression Imports Microsoft.CodeAnalysis.VisualBasic.UseCoalesceExpression Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.UseCoalesceExpression Public Class UseCoalesceExpressionForNullableTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicUseCoalesceExpressionForNullableDiagnosticAnalyzer(), New UseCoalesceExpressionForNullableCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)> Public Async Function TestOnLeft_Equals() As Task Await TestInRegularAndScriptAsync( " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = [||]If (Not x.HasValue, y, x.Value) End Sub End Class", " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = If(x, y) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)> Public Async Function TestOnLeft_NotEquals() As Task Await TestInRegularAndScriptAsync( " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = [||]If(x.HasValue, x.Value, y) End Sub End Class", " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = If(x, y) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)> Public Async Function TestComplexExpression() As Task Await TestInRegularAndScriptAsync( " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = [||]If (Not (x + y).HasValue, y, (x + y).Value) End Sub End Class", " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = If((x + y), y) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)> Public Async Function TestParens1() As Task Await TestInRegularAndScriptAsync( " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = [||]If ((Not x.HasValue), y, x.Value) End Sub End Class", " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z = If(x, y) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)> Public Async Function TestFixAll1() As Task Await TestInRegularAndScriptAsync( " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z1 = {|FixAllInDocument:If|} (Not x.HasValue, y, x.Value) Dim z2 = If(x.HasValue, x.Value, y) End Sub End Class", " Imports System Class C Sub M(x as Integer?, y as Integer?) Dim z1 = If(x, y) Dim z2 = If(x, y) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)> Public Async Function TestFixAll2() As Task Await TestInRegularAndScriptAsync( " Imports System Class C Sub M(x as Integer?, y as Integer?, z as Integer?) dim w = {|FixAllInDocument:If|} (x.HasValue, x.Value, If(y.HasValue, y.Value, z)) End Sub End Class", " Imports System Class C Sub M(x as Integer?, y as Integer?, z as Integer?) dim w = If(x, If(y, z)) End Sub End Class") End Function <WorkItem(17028, "https://github.com/dotnet/roslyn/issues/17028")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)> Public Async Function TestInExpressionOfT() As Task Await TestInRegularAndScriptAsync( " Imports System Imports System.Linq.Expressions Class C Sub M(x as integer?, y as integer) dim e as Expression(of Func(of integer)) = function() [||]If (x.HasValue, x.Value, y) End Sub End Class", " Imports System Imports System.Linq.Expressions Class C Sub M(x as integer?, y as integer) dim e as Expression(of Func(of integer)) = function() {|Warning:If(x, y)|} End Sub End Class") End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/TestUtilities/Classification/FormattedClassifications.XmlDoc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.Classification; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification { public static partial class FormattedClassifications { public static class XmlDoc { [DebuggerStepThrough] public static FormattedClassification AttributeName(string text) => New(text, ClassificationTypeNames.XmlDocCommentAttributeName); [DebuggerStepThrough] public static FormattedClassification AttributeQuotes(string text) => New(text, ClassificationTypeNames.XmlDocCommentAttributeQuotes); [DebuggerStepThrough] public static FormattedClassification AttributeValue(string text) => New(text, ClassificationTypeNames.XmlDocCommentAttributeValue); [DebuggerStepThrough] public static FormattedClassification CDataSection(string text) => New(text, ClassificationTypeNames.XmlDocCommentCDataSection); [DebuggerStepThrough] public static FormattedClassification Comment(string text) => New(text, ClassificationTypeNames.XmlDocCommentComment); [DebuggerStepThrough] public static FormattedClassification Delimiter(string text) => New(text, ClassificationTypeNames.XmlDocCommentDelimiter); [DebuggerStepThrough] public static FormattedClassification EntityReference(string text) => New(text, ClassificationTypeNames.XmlDocCommentEntityReference); [DebuggerStepThrough] public static FormattedClassification Name(string text) => New(text, ClassificationTypeNames.XmlDocCommentName); [DebuggerStepThrough] public static FormattedClassification ProcessingInstruction(string text) => New(text, ClassificationTypeNames.XmlDocCommentProcessingInstruction); [DebuggerStepThrough] public static FormattedClassification Text(string text) => New(text, ClassificationTypeNames.XmlDocCommentText); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.Classification; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification { public static partial class FormattedClassifications { public static class XmlDoc { [DebuggerStepThrough] public static FormattedClassification AttributeName(string text) => New(text, ClassificationTypeNames.XmlDocCommentAttributeName); [DebuggerStepThrough] public static FormattedClassification AttributeQuotes(string text) => New(text, ClassificationTypeNames.XmlDocCommentAttributeQuotes); [DebuggerStepThrough] public static FormattedClassification AttributeValue(string text) => New(text, ClassificationTypeNames.XmlDocCommentAttributeValue); [DebuggerStepThrough] public static FormattedClassification CDataSection(string text) => New(text, ClassificationTypeNames.XmlDocCommentCDataSection); [DebuggerStepThrough] public static FormattedClassification Comment(string text) => New(text, ClassificationTypeNames.XmlDocCommentComment); [DebuggerStepThrough] public static FormattedClassification Delimiter(string text) => New(text, ClassificationTypeNames.XmlDocCommentDelimiter); [DebuggerStepThrough] public static FormattedClassification EntityReference(string text) => New(text, ClassificationTypeNames.XmlDocCommentEntityReference); [DebuggerStepThrough] public static FormattedClassification Name(string text) => New(text, ClassificationTypeNames.XmlDocCommentName); [DebuggerStepThrough] public static FormattedClassification ProcessingInstruction(string text) => New(text, ClassificationTypeNames.XmlDocCommentProcessingInstruction); [DebuggerStepThrough] public static FormattedClassification Text(string text) => New(text, ClassificationTypeNames.XmlDocCommentText); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Portable/Syntax/NamespaceDeclarationSyntaxReference.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.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' this is a SyntaxReference implementation that lazily translates the result (SyntaxNode) of the original syntax reference ''' to other one. ''' </summary> Friend Class NamespaceDeclarationSyntaxReference Inherits TranslationSyntaxReference Public Sub New(reference As SyntaxReference) MyBase.New(reference) End Sub Protected Overrides Function Translate(reference As SyntaxReference, cancellationToken As CancellationToken) As SyntaxNode Dim node = reference.GetSyntax(cancellationToken) ' If the node is a name syntax, it's something like "X" or "X.Y" in : ' Namespace X.Y.Z ' We want to return the full NamespaceStatementSyntax. While TypeOf node Is NameSyntax node = node.Parent End While Debug.Assert(TypeOf node Is CompilationUnitSyntax OrElse TypeOf node Is NamespaceStatementSyntax) Return node 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.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' this is a SyntaxReference implementation that lazily translates the result (SyntaxNode) of the original syntax reference ''' to other one. ''' </summary> Friend Class NamespaceDeclarationSyntaxReference Inherits TranslationSyntaxReference Public Sub New(reference As SyntaxReference) MyBase.New(reference) End Sub Protected Overrides Function Translate(reference As SyntaxReference, cancellationToken As CancellationToken) As SyntaxNode Dim node = reference.GetSyntax(cancellationToken) ' If the node is a name syntax, it's something like "X" or "X.Y" in : ' Namespace X.Y.Z ' We want to return the full NamespaceStatementSyntax. While TypeOf node Is NameSyntax node = node.Parent End While Debug.Assert(TypeOf node Is CompilationUnitSyntax OrElse TypeOf node Is NamespaceStatementSyntax) Return node End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncStateMachine.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The class that represents a translated async or async-iterator method. /// </summary> internal sealed class AsyncStateMachine : StateMachineTypeSymbol { private readonly TypeKind _typeKind; private readonly MethodSymbol _constructor; private readonly ImmutableArray<NamedTypeSymbol> _interfaces; internal readonly TypeSymbol IteratorElementType; // only for async-iterators public AsyncStateMachine(VariableSlotAllocator variableAllocatorOpt, TypeCompilationState compilationState, MethodSymbol asyncMethod, int asyncMethodOrdinal, TypeKind typeKind) : base(variableAllocatorOpt, compilationState, asyncMethod, asyncMethodOrdinal) { _typeKind = typeKind; CSharpCompilation compilation = asyncMethod.DeclaringCompilation; var interfaces = ArrayBuilder<NamedTypeSymbol>.GetInstance(); bool isIterator = asyncMethod.IsIterator; if (isIterator) { var elementType = TypeMap.SubstituteType(asyncMethod.IteratorElementTypeWithAnnotations).Type; this.IteratorElementType = elementType; bool isEnumerable = asyncMethod.IsAsyncReturningIAsyncEnumerable(compilation); if (isEnumerable) { // IAsyncEnumerable<TResult> interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T).Construct(elementType)); } // IAsyncEnumerator<TResult> interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T).Construct(elementType)); // IValueTaskSource<bool> interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T).Construct(compilation.GetSpecialType(SpecialType.System_Boolean))); // IValueTaskSource interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource)); // IAsyncDisposable interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable)); } interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine)); _interfaces = interfaces.ToImmutableAndFree(); _constructor = isIterator ? (MethodSymbol)new IteratorConstructor(this) : new AsyncConstructor(this); } public override TypeKind TypeKind { get { return _typeKind; } } internal override MethodSymbol Constructor { get { return _constructor; } } internal override bool IsRecord => false; internal override bool IsRecordStruct => false; internal override bool HasPossibleWellKnownCloneMethod() => false; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) { return _interfaces; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The class that represents a translated async or async-iterator method. /// </summary> internal sealed class AsyncStateMachine : StateMachineTypeSymbol { private readonly TypeKind _typeKind; private readonly MethodSymbol _constructor; private readonly ImmutableArray<NamedTypeSymbol> _interfaces; internal readonly TypeSymbol IteratorElementType; // only for async-iterators public AsyncStateMachine(VariableSlotAllocator variableAllocatorOpt, TypeCompilationState compilationState, MethodSymbol asyncMethod, int asyncMethodOrdinal, TypeKind typeKind) : base(variableAllocatorOpt, compilationState, asyncMethod, asyncMethodOrdinal) { _typeKind = typeKind; CSharpCompilation compilation = asyncMethod.DeclaringCompilation; var interfaces = ArrayBuilder<NamedTypeSymbol>.GetInstance(); bool isIterator = asyncMethod.IsIterator; if (isIterator) { var elementType = TypeMap.SubstituteType(asyncMethod.IteratorElementTypeWithAnnotations).Type; this.IteratorElementType = elementType; bool isEnumerable = asyncMethod.IsAsyncReturningIAsyncEnumerable(compilation); if (isEnumerable) { // IAsyncEnumerable<TResult> interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T).Construct(elementType)); } // IAsyncEnumerator<TResult> interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T).Construct(elementType)); // IValueTaskSource<bool> interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T).Construct(compilation.GetSpecialType(SpecialType.System_Boolean))); // IValueTaskSource interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource)); // IAsyncDisposable interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable)); } interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine)); _interfaces = interfaces.ToImmutableAndFree(); _constructor = isIterator ? (MethodSymbol)new IteratorConstructor(this) : new AsyncConstructor(this); } public override TypeKind TypeKind { get { return _typeKind; } } internal override MethodSymbol Constructor { get { return _constructor; } } internal override bool IsRecord => false; internal override bool IsRecordStruct => false; internal override bool HasPossibleWellKnownCloneMethod() => false; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) { return _interfaces; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/VisualBasic/Portable/Formatting/DefaultOperationProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting ' the default provider that will be called by the engine at the end of provider's chain. ' there is no way for a user to be remove this provider. ' ' to reduce number of unnecessary heap allocations, most of them just return null. Friend NotInheritable Class DefaultOperationProvider Inherits CompatAbstractFormattingRule Public Shared ReadOnly Instance As New DefaultOperationProvider() Private ReadOnly _options As SyntaxFormattingOptions Private Sub New() MyClass.New(VisualBasicSyntaxFormattingOptions.Default) End Sub Private Sub New(options As SyntaxFormattingOptions) _options = options End Sub Public Overrides Function WithOptions(options As SyntaxFormattingOptions) As AbstractFormattingRule If _options.SeparateImportDirectiveGroups = options.SeparateImportDirectiveGroups Then Return Me End If Return New DefaultOperationProvider(options) End Function Public Overrides Sub AddSuppressOperationsSlow(operations As List(Of SuppressOperation), node As SyntaxNode, ByRef nextAction As NextSuppressOperationAction) End Sub Public Overrides Sub AddAnchorIndentationOperationsSlow(operations As List(Of AnchorIndentationOperation), node As SyntaxNode, ByRef nextAction As NextAnchorIndentationOperationAction) End Sub Public Overrides Sub AddIndentBlockOperationsSlow(operations As List(Of IndentBlockOperation), node As SyntaxNode, ByRef nextAction As NextIndentBlockOperationAction) End Sub Public Overrides Sub AddAlignTokensOperationsSlow(operations As List(Of AlignTokensOperation), node As SyntaxNode, ByRef nextAction As NextAlignTokensOperationAction) End Sub <PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowCaptures:=False, AllowImplicitBoxing:=False)> Public Overrides Function GetAdjustNewLinesOperationSlow( ByRef previousToken As SyntaxToken, ByRef currentToken As SyntaxToken, ByRef nextOperation As NextGetAdjustNewLinesOperation) As AdjustNewLinesOperation If previousToken.Parent Is Nothing Then Return Nothing End If Dim combinedTrivia = (previousToken.TrailingTrivia, currentToken.LeadingTrivia) Dim lastTrivia = LastOrDefaultTrivia( combinedTrivia, Function(trivia As SyntaxTrivia) ColonOrLineContinuationTrivia(trivia)) If lastTrivia.RawKind = SyntaxKind.ColonTrivia Then Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines) ElseIf lastTrivia.RawKind = SyntaxKind.LineContinuationTrivia AndAlso previousToken.Parent.GetAncestorsOrThis(Of SyntaxNode)().Any(Function(node As SyntaxNode) IsSingleLineIfOrElseClauseSyntax(node)) Then Return Nothing End If ' return line break operation after statement terminator token so that we can enforce ' indentation for the line Dim previousStatement As StatementSyntax = Nothing If previousToken.IsLastTokenOfStatement(statement:=previousStatement) AndAlso ContainEndOfLine(previousToken, currentToken) AndAlso currentToken.Kind <> SyntaxKind.EmptyToken Then Return AdjustNewLinesBetweenStatements(previousStatement, currentToken) End If If previousToken.Kind = SyntaxKind.GreaterThanToken AndAlso previousToken.Parent IsNot Nothing AndAlso TypeOf previousToken.Parent Is AttributeListSyntax Then ' This AttributeList is the last applied attribute ' If this AttributeList belongs to a parameter then apply no line operation If previousToken.Parent.Parent IsNot Nothing AndAlso TypeOf previousToken.Parent.Parent Is ParameterSyntax Then Return Nothing End If Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines) End If If currentToken.Kind = SyntaxKind.LessThanToken AndAlso currentToken.Parent IsNot Nothing AndAlso TypeOf currentToken.Parent Is AttributeListSyntax Then ' The case of the previousToken belonging to another AttributeList is handled in the previous condition If (previousToken.Kind = SyntaxKind.CommaToken OrElse previousToken.Kind = SyntaxKind.OpenParenToken) AndAlso currentToken.Parent.Parent IsNot Nothing AndAlso TypeOf currentToken.Parent.Parent Is ParameterSyntax Then Return Nothing End If Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines) End If ' return line break operation after xml tag token so that we can enforce indentation for the xml tag ' the very first xml literal tag case If IsFirstXmlTag(currentToken) Then Return Nothing End If Dim xmlDeclaration = TryCast(previousToken.Parent, XmlDeclarationSyntax) If xmlDeclaration IsNot Nothing AndAlso xmlDeclaration.GetLastToken(includeZeroWidth:=True) = previousToken Then Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines) End If If TypeOf previousToken.Parent Is XmlNodeSyntax OrElse TypeOf currentToken.Parent Is XmlNodeSyntax Then Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines) End If Return Nothing End Function Private Function AdjustNewLinesBetweenStatements( previousStatement As StatementSyntax, currentToken As SyntaxToken) As AdjustNewLinesOperation ' if the user is separating import-groups, And we're between two imports, and these ' imports *should* be separated, then do so (if the imports were already properly ' sorted). If currentToken.Kind() = SyntaxKind.ImportsKeyword AndAlso TypeOf currentToken.Parent Is ImportsStatementSyntax AndAlso TypeOf previousStatement Is ImportsStatementSyntax Then Dim previousImports = DirectCast(previousStatement, ImportsStatementSyntax) Dim currentImports = DirectCast(currentToken.Parent, ImportsStatementSyntax) If _options.SeparateImportDirectiveGroups AndAlso ImportsOrganizer.NeedsGrouping(previousImports, currentImports) Then Dim [imports] = DirectCast(previousImports.Parent, CompilationUnitSyntax).Imports If [imports].IsSorted(ImportsStatementComparer.SystemFirstInstance) OrElse [imports].IsSorted(ImportsStatementComparer.NormalInstance) Then ' Force at least one blank line here. Return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.PreserveLines) End If End If End If ' For any other two statements we will normally ensure at least one new-line between ' them. Return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines) End Function Private Shared Function IsSingleLineIfOrElseClauseSyntax(node As SyntaxNode) As Boolean Return TypeOf node Is SingleLineIfStatementSyntax OrElse TypeOf node Is SingleLineElseClauseSyntax End Function Private Shared Function ColonOrLineContinuationTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.RawKind = SyntaxKind.ColonTrivia OrElse trivia.RawKind = SyntaxKind.LineContinuationTrivia End Function <PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowCaptures:=False, AllowImplicitBoxing:=False)> Private Shared Function LastOrDefaultTrivia(triviaListPair As (SyntaxTriviaList, SyntaxTriviaList), predicate As Func(Of SyntaxTrivia, Boolean)) As SyntaxTrivia For Each trivia In triviaListPair.Item2.Reverse() If predicate(trivia) Then Return trivia End If Next For Each trivia In triviaListPair.Item1.Reverse() If predicate(trivia) Then Return trivia End If Next Return Nothing End Function Private Shared Function ContainEndOfLine(previousToken As SyntaxToken, nextToken As SyntaxToken) As Boolean Return previousToken.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia) OrElse nextToken.LeadingTrivia.Any(SyntaxKind.EndOfLineTrivia) End Function Private Shared Function IsFirstXmlTag(currentToken As SyntaxToken) As Boolean Dim xmlDeclaration = TryCast(currentToken.Parent, XmlDeclarationSyntax) If xmlDeclaration IsNot Nothing AndAlso xmlDeclaration.LessThanQuestionToken = currentToken AndAlso TypeOf xmlDeclaration.Parent Is XmlDocumentSyntax AndAlso Not TypeOf xmlDeclaration.Parent.Parent Is XmlNodeSyntax Then Return True End If Dim startTag = TryCast(currentToken.Parent, XmlElementStartTagSyntax) If startTag IsNot Nothing AndAlso startTag.LessThanToken = currentToken AndAlso TypeOf startTag.Parent Is XmlElementSyntax AndAlso Not TypeOf startTag.Parent.Parent Is XmlNodeSyntax Then Return True End If Dim emptyTag = TryCast(currentToken.Parent, XmlEmptyElementSyntax) If emptyTag IsNot Nothing AndAlso emptyTag.LessThanToken = currentToken AndAlso Not TypeOf emptyTag.Parent Is XmlNodeSyntax Then Return True End If Return False End Function ' return 1 space for every token pairs as a default operation Public Overrides Function GetAdjustSpacesOperationSlow(ByRef previousToken As SyntaxToken, ByRef currentToken As SyntaxToken, ByRef nextOperation As NextGetAdjustSpacesOperation) As AdjustSpacesOperation If previousToken.Kind = SyntaxKind.ColonToken AndAlso TypeOf previousToken.Parent Is LabelStatementSyntax AndAlso currentToken.Kind <> SyntaxKind.EndOfFileToken Then Return FormattingOperations.CreateAdjustSpacesOperation(1, AdjustSpacesOption.DynamicSpaceToIndentationIfOnSingleLine) End If Dim space As Integer = If(currentToken.Kind = SyntaxKind.EndOfFileToken, 0, 1) Return FormattingOperations.CreateAdjustSpacesOperation(space, AdjustSpacesOption.DefaultSpacesIfOnSingleLine) 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 Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting ' the default provider that will be called by the engine at the end of provider's chain. ' there is no way for a user to be remove this provider. ' ' to reduce number of unnecessary heap allocations, most of them just return null. Friend NotInheritable Class DefaultOperationProvider Inherits CompatAbstractFormattingRule Public Shared ReadOnly Instance As New DefaultOperationProvider() Private ReadOnly _options As SyntaxFormattingOptions Private Sub New() MyClass.New(VisualBasicSyntaxFormattingOptions.Default) End Sub Private Sub New(options As SyntaxFormattingOptions) _options = options End Sub Public Overrides Function WithOptions(options As SyntaxFormattingOptions) As AbstractFormattingRule If _options.SeparateImportDirectiveGroups = options.SeparateImportDirectiveGroups Then Return Me End If Return New DefaultOperationProvider(options) End Function Public Overrides Sub AddSuppressOperationsSlow(operations As List(Of SuppressOperation), node As SyntaxNode, ByRef nextAction As NextSuppressOperationAction) End Sub Public Overrides Sub AddAnchorIndentationOperationsSlow(operations As List(Of AnchorIndentationOperation), node As SyntaxNode, ByRef nextAction As NextAnchorIndentationOperationAction) End Sub Public Overrides Sub AddIndentBlockOperationsSlow(operations As List(Of IndentBlockOperation), node As SyntaxNode, ByRef nextAction As NextIndentBlockOperationAction) End Sub Public Overrides Sub AddAlignTokensOperationsSlow(operations As List(Of AlignTokensOperation), node As SyntaxNode, ByRef nextAction As NextAlignTokensOperationAction) End Sub <PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowCaptures:=False, AllowImplicitBoxing:=False)> Public Overrides Function GetAdjustNewLinesOperationSlow( ByRef previousToken As SyntaxToken, ByRef currentToken As SyntaxToken, ByRef nextOperation As NextGetAdjustNewLinesOperation) As AdjustNewLinesOperation If previousToken.Parent Is Nothing Then Return Nothing End If Dim combinedTrivia = (previousToken.TrailingTrivia, currentToken.LeadingTrivia) Dim lastTrivia = LastOrDefaultTrivia( combinedTrivia, Function(trivia As SyntaxTrivia) ColonOrLineContinuationTrivia(trivia)) If lastTrivia.RawKind = SyntaxKind.ColonTrivia Then Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines) ElseIf lastTrivia.RawKind = SyntaxKind.LineContinuationTrivia AndAlso previousToken.Parent.GetAncestorsOrThis(Of SyntaxNode)().Any(Function(node As SyntaxNode) IsSingleLineIfOrElseClauseSyntax(node)) Then Return Nothing End If ' return line break operation after statement terminator token so that we can enforce ' indentation for the line Dim previousStatement As StatementSyntax = Nothing If previousToken.IsLastTokenOfStatement(statement:=previousStatement) AndAlso ContainEndOfLine(previousToken, currentToken) AndAlso currentToken.Kind <> SyntaxKind.EmptyToken Then Return AdjustNewLinesBetweenStatements(previousStatement, currentToken) End If If previousToken.Kind = SyntaxKind.GreaterThanToken AndAlso previousToken.Parent IsNot Nothing AndAlso TypeOf previousToken.Parent Is AttributeListSyntax Then ' This AttributeList is the last applied attribute ' If this AttributeList belongs to a parameter then apply no line operation If previousToken.Parent.Parent IsNot Nothing AndAlso TypeOf previousToken.Parent.Parent Is ParameterSyntax Then Return Nothing End If Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines) End If If currentToken.Kind = SyntaxKind.LessThanToken AndAlso currentToken.Parent IsNot Nothing AndAlso TypeOf currentToken.Parent Is AttributeListSyntax Then ' The case of the previousToken belonging to another AttributeList is handled in the previous condition If (previousToken.Kind = SyntaxKind.CommaToken OrElse previousToken.Kind = SyntaxKind.OpenParenToken) AndAlso currentToken.Parent.Parent IsNot Nothing AndAlso TypeOf currentToken.Parent.Parent Is ParameterSyntax Then Return Nothing End If Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines) End If ' return line break operation after xml tag token so that we can enforce indentation for the xml tag ' the very first xml literal tag case If IsFirstXmlTag(currentToken) Then Return Nothing End If Dim xmlDeclaration = TryCast(previousToken.Parent, XmlDeclarationSyntax) If xmlDeclaration IsNot Nothing AndAlso xmlDeclaration.GetLastToken(includeZeroWidth:=True) = previousToken Then Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines) End If If TypeOf previousToken.Parent Is XmlNodeSyntax OrElse TypeOf currentToken.Parent Is XmlNodeSyntax Then Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines) End If Return Nothing End Function Private Function AdjustNewLinesBetweenStatements( previousStatement As StatementSyntax, currentToken As SyntaxToken) As AdjustNewLinesOperation ' if the user is separating import-groups, And we're between two imports, and these ' imports *should* be separated, then do so (if the imports were already properly ' sorted). If currentToken.Kind() = SyntaxKind.ImportsKeyword AndAlso TypeOf currentToken.Parent Is ImportsStatementSyntax AndAlso TypeOf previousStatement Is ImportsStatementSyntax Then Dim previousImports = DirectCast(previousStatement, ImportsStatementSyntax) Dim currentImports = DirectCast(currentToken.Parent, ImportsStatementSyntax) If _options.SeparateImportDirectiveGroups AndAlso ImportsOrganizer.NeedsGrouping(previousImports, currentImports) Then Dim [imports] = DirectCast(previousImports.Parent, CompilationUnitSyntax).Imports If [imports].IsSorted(ImportsStatementComparer.SystemFirstInstance) OrElse [imports].IsSorted(ImportsStatementComparer.NormalInstance) Then ' Force at least one blank line here. Return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.PreserveLines) End If End If End If ' For any other two statements we will normally ensure at least one new-line between ' them. Return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines) End Function Private Shared Function IsSingleLineIfOrElseClauseSyntax(node As SyntaxNode) As Boolean Return TypeOf node Is SingleLineIfStatementSyntax OrElse TypeOf node Is SingleLineElseClauseSyntax End Function Private Shared Function ColonOrLineContinuationTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.RawKind = SyntaxKind.ColonTrivia OrElse trivia.RawKind = SyntaxKind.LineContinuationTrivia End Function <PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowCaptures:=False, AllowImplicitBoxing:=False)> Private Shared Function LastOrDefaultTrivia(triviaListPair As (SyntaxTriviaList, SyntaxTriviaList), predicate As Func(Of SyntaxTrivia, Boolean)) As SyntaxTrivia For Each trivia In triviaListPair.Item2.Reverse() If predicate(trivia) Then Return trivia End If Next For Each trivia In triviaListPair.Item1.Reverse() If predicate(trivia) Then Return trivia End If Next Return Nothing End Function Private Shared Function ContainEndOfLine(previousToken As SyntaxToken, nextToken As SyntaxToken) As Boolean Return previousToken.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia) OrElse nextToken.LeadingTrivia.Any(SyntaxKind.EndOfLineTrivia) End Function Private Shared Function IsFirstXmlTag(currentToken As SyntaxToken) As Boolean Dim xmlDeclaration = TryCast(currentToken.Parent, XmlDeclarationSyntax) If xmlDeclaration IsNot Nothing AndAlso xmlDeclaration.LessThanQuestionToken = currentToken AndAlso TypeOf xmlDeclaration.Parent Is XmlDocumentSyntax AndAlso Not TypeOf xmlDeclaration.Parent.Parent Is XmlNodeSyntax Then Return True End If Dim startTag = TryCast(currentToken.Parent, XmlElementStartTagSyntax) If startTag IsNot Nothing AndAlso startTag.LessThanToken = currentToken AndAlso TypeOf startTag.Parent Is XmlElementSyntax AndAlso Not TypeOf startTag.Parent.Parent Is XmlNodeSyntax Then Return True End If Dim emptyTag = TryCast(currentToken.Parent, XmlEmptyElementSyntax) If emptyTag IsNot Nothing AndAlso emptyTag.LessThanToken = currentToken AndAlso Not TypeOf emptyTag.Parent Is XmlNodeSyntax Then Return True End If Return False End Function ' return 1 space for every token pairs as a default operation Public Overrides Function GetAdjustSpacesOperationSlow(ByRef previousToken As SyntaxToken, ByRef currentToken As SyntaxToken, ByRef nextOperation As NextGetAdjustSpacesOperation) As AdjustSpacesOperation If previousToken.Kind = SyntaxKind.ColonToken AndAlso TypeOf previousToken.Parent Is LabelStatementSyntax AndAlso currentToken.Kind <> SyntaxKind.EndOfFileToken Then Return FormattingOperations.CreateAdjustSpacesOperation(1, AdjustSpacesOption.DynamicSpaceToIndentationIfOnSingleLine) End If Dim space As Integer = If(currentToken.Kind = SyntaxKind.EndOfFileToken, 0, 1) Return FormattingOperations.CreateAdjustSpacesOperation(space, AdjustSpacesOption.DefaultSpacesIfOnSingleLine) End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/EditorConfigSettings/NamingStyle/View/ColumnViews/NamingStylesStyleControl.xaml
<UserControl x:Class="Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.NamingStyle.View.NamingStylesStyleControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:namingStyleViewModel="clr-namespace:Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.NamingStyle.ViewModel" d:DataContext="{d:DesignInstance Type=namingStyleViewModel:NamingStylesStyleViewModel}" mc:Ignorable="d" x:ClassModifier="internal"> <Grid x:Name="RootGrid"> <ComboBox x:Name="StyleComboBox" ItemsSource="{Binding StyleValues}" SelectedValue="{Binding SelectedStyleValue}" ToolTip="{Binding StyleToolTip}" AutomationProperties.Name="{Binding StyleAutomationName}" SelectionChanged="StyleComboBox_SelectionChanged"/> </Grid> </UserControl>
<UserControl x:Class="Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.NamingStyle.View.NamingStylesStyleControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:namingStyleViewModel="clr-namespace:Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.NamingStyle.ViewModel" d:DataContext="{d:DesignInstance Type=namingStyleViewModel:NamingStylesStyleViewModel}" mc:Ignorable="d" x:ClassModifier="internal"> <Grid x:Name="RootGrid"> <ComboBox x:Name="StyleComboBox" ItemsSource="{Binding StyleValues}" SelectedValue="{Binding SelectedStyleValue}" ToolTip="{Binding StyleToolTip}" AutomationProperties.Name="{Binding StyleAutomationName}" SelectionChanged="StyleComboBox_SelectionChanged"/> </Grid> </UserControl>
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/Core/Portable/RQName/Nodes/RQPropertyBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal abstract class RQPropertyBase : RQMethodOrProperty { public RQPropertyBase( RQUnconstructedType containingType, RQMethodPropertyOrEventName memberName, int typeParameterCount, IList<RQParameter> parameters) : base(containingType, memberName, typeParameterCount, parameters) { } protected override string RQKeyword { get { return RQNameStrings.Prop; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal abstract class RQPropertyBase : RQMethodOrProperty { public RQPropertyBase( RQUnconstructedType containingType, RQMethodPropertyOrEventName memberName, int typeParameterCount, IList<RQParameter> parameters) : base(containingType, memberName, typeParameterCount, parameters) { } protected override string RQKeyword { get { return RQNameStrings.Prop; } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Portable/Parser/BlockContexts/DoLoopBlockContext.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------- ' Contains the definition of the BlockContext '----------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend NotInheritable Class DoLoopBlockContext Inherits ExecutableStatementContext Friend Sub New(statement As StatementSyntax, prevContext As BlockContext) MyBase.New(If(DirectCast(statement, DoStatementSyntax).WhileOrUntilClause Is Nothing, SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock), statement, prevContext) End Sub Friend Overrides Function CreateBlockSyntax(statement As StatementSyntax) As VisualBasicSyntaxNode Dim doStmt As DoStatementSyntax = Nothing Dim loopStmt As LoopStatementSyntax = DirectCast(statement, LoopStatementSyntax) GetBeginEndStatements(doStmt, loopStmt) Dim kind As SyntaxKind = BlockKind If kind = SyntaxKind.DoWhileLoopBlock AndAlso loopStmt.WhileOrUntilClause IsNot Nothing Then Dim whileUntilClause = loopStmt.WhileOrUntilClause ' Error: the loop has a condition in both header and trailer. Dim keyword = Parser.ReportSyntaxError(whileUntilClause.WhileOrUntilKeyword, ERRID.ERR_LoopDoubleCondition) Dim errors = whileUntilClause.GetDiagnostics whileUntilClause = SyntaxFactory.WhileOrUntilClause(whileUntilClause.Kind, DirectCast(keyword, KeywordSyntax), whileUntilClause.Condition) If errors IsNot Nothing Then whileUntilClause = DirectCast(whileUntilClause.SetDiagnostics(errors), WhileOrUntilClauseSyntax) End If loopStmt = SyntaxFactory.LoopStatement(loopStmt.Kind, loopStmt.LoopKeyword, whileUntilClause) End If If kind = SyntaxKind.SimpleDoLoopBlock AndAlso loopStmt.WhileOrUntilClause IsNot Nothing Then ' Set the Do Loop kind now that the bottom is known. kind = If(loopStmt.Kind = SyntaxKind.LoopWhileStatement, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock) ElseIf doStmt.WhileOrUntilClause IsNot Nothing Then kind = If(doStmt.Kind = SyntaxKind.DoWhileStatement, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock) End If Dim result = SyntaxFactory.DoLoopBlock(kind, doStmt, Body(), loopStmt) FreeStatements() Return result End Function Friend Overrides Function KindEndsBlock(kind As SyntaxKind) As Boolean Select Case kind Case SyntaxKind.SimpleLoopStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.LoopUntilStatement Return True Case Else Return False End Select 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------- ' Contains the definition of the BlockContext '----------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend NotInheritable Class DoLoopBlockContext Inherits ExecutableStatementContext Friend Sub New(statement As StatementSyntax, prevContext As BlockContext) MyBase.New(If(DirectCast(statement, DoStatementSyntax).WhileOrUntilClause Is Nothing, SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock), statement, prevContext) End Sub Friend Overrides Function CreateBlockSyntax(statement As StatementSyntax) As VisualBasicSyntaxNode Dim doStmt As DoStatementSyntax = Nothing Dim loopStmt As LoopStatementSyntax = DirectCast(statement, LoopStatementSyntax) GetBeginEndStatements(doStmt, loopStmt) Dim kind As SyntaxKind = BlockKind If kind = SyntaxKind.DoWhileLoopBlock AndAlso loopStmt.WhileOrUntilClause IsNot Nothing Then Dim whileUntilClause = loopStmt.WhileOrUntilClause ' Error: the loop has a condition in both header and trailer. Dim keyword = Parser.ReportSyntaxError(whileUntilClause.WhileOrUntilKeyword, ERRID.ERR_LoopDoubleCondition) Dim errors = whileUntilClause.GetDiagnostics whileUntilClause = SyntaxFactory.WhileOrUntilClause(whileUntilClause.Kind, DirectCast(keyword, KeywordSyntax), whileUntilClause.Condition) If errors IsNot Nothing Then whileUntilClause = DirectCast(whileUntilClause.SetDiagnostics(errors), WhileOrUntilClauseSyntax) End If loopStmt = SyntaxFactory.LoopStatement(loopStmt.Kind, loopStmt.LoopKeyword, whileUntilClause) End If If kind = SyntaxKind.SimpleDoLoopBlock AndAlso loopStmt.WhileOrUntilClause IsNot Nothing Then ' Set the Do Loop kind now that the bottom is known. kind = If(loopStmt.Kind = SyntaxKind.LoopWhileStatement, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock) ElseIf doStmt.WhileOrUntilClause IsNot Nothing Then kind = If(doStmt.Kind = SyntaxKind.DoWhileStatement, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock) End If Dim result = SyntaxFactory.DoLoopBlock(kind, doStmt, Body(), loopStmt) FreeStatements() Return result End Function Friend Overrides Function KindEndsBlock(kind As SyntaxKind) As Boolean Select Case kind Case SyntaxKind.SimpleLoopStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.LoopUntilStatement Return True Case Else Return False End Select End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/Core.Wpf/Peek/DefinitionPeekableItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Language.Intellisense; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek { internal class DefinitionPeekableItem : PeekableItem { private readonly Workspace _workspace; private readonly ProjectId _projectId; private readonly SymbolKey _symbolKey; private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; private readonly IGlobalOptionService _globalOptions; public DefinitionPeekableItem( Workspace workspace, ProjectId projectId, SymbolKey symbolKey, IPeekResultFactory peekResultFactory, IMetadataAsSourceFileService metadataAsSourceService, IGlobalOptionService globalOptions) : base(peekResultFactory) { _workspace = workspace; _projectId = projectId; _symbolKey = symbolKey; _metadataAsSourceFileService = metadataAsSourceService; _globalOptions = globalOptions; } public override IEnumerable<IPeekRelationship> Relationships { get { return SpecializedCollections.SingletonEnumerable(PredefinedPeekRelationships.Definitions); } } public override IPeekResultSource GetOrCreateResultSource(string relationshipName) => new ResultSource(this); private sealed class ResultSource : IPeekResultSource { private readonly DefinitionPeekableItem _peekableItem; public ResultSource(DefinitionPeekableItem peekableItem) => _peekableItem = peekableItem; public void FindResults(string relationshipName, IPeekResultCollection resultCollection, CancellationToken cancellationToken, IFindPeekResultsCallback callback) { if (relationshipName != PredefinedPeekRelationships.Definitions.Name) { return; } // Note: this is called on a background thread, but we must block the thread since the API doesn't support proper asynchrony. var workspace = _peekableItem._workspace; var solution = workspace.CurrentSolution; var project = solution.GetProject(_peekableItem._projectId); var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken); var symbol = _peekableItem._symbolKey.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken).Symbol; if (symbol == null) { callback.ReportFailure(new Exception(EditorFeaturesResources.No_information_found)); return; } var sourceLocations = symbol.Locations.Where(l => l.IsInSource).ToList(); if (!sourceLocations.Any()) { // It's a symbol from metadata, so we want to go produce it from metadata var options = _peekableItem._globalOptions.GetMetadataAsSourceOptions(project.LanguageServices); var declarationFile = _peekableItem._metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, signaturesOnly: false, options, cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken); var peekDisplayInfo = new PeekResultDisplayInfo(declarationFile.DocumentTitle, declarationFile.DocumentTooltip, declarationFile.DocumentTitle, declarationFile.DocumentTooltip); var identifierSpan = declarationFile.IdentifierLocation.GetLineSpan().Span; var entityOfInterestSpan = PeekHelpers.GetEntityOfInterestSpan(symbol, workspace, declarationFile.IdentifierLocation, cancellationToken); resultCollection.Add(PeekHelpers.CreateDocumentPeekResult(declarationFile.FilePath, identifierSpan, entityOfInterestSpan, peekDisplayInfo, _peekableItem.PeekResultFactory, isReadOnly: true)); } var processedSourceLocations = 0; foreach (var declaration in sourceLocations) { var declarationLocation = declaration.GetMappedLineSpan(); var entityOfInterestSpan = PeekHelpers.GetEntityOfInterestSpan(symbol, workspace, declaration, cancellationToken); resultCollection.Add(PeekHelpers.CreateDocumentPeekResult(declarationLocation.Path, declarationLocation.Span, entityOfInterestSpan, _peekableItem.PeekResultFactory)); callback.ReportProgress(100 * ++processedSourceLocations / sourceLocations.Count); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Language.Intellisense; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek { internal class DefinitionPeekableItem : PeekableItem { private readonly Workspace _workspace; private readonly ProjectId _projectId; private readonly SymbolKey _symbolKey; private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; private readonly IGlobalOptionService _globalOptions; public DefinitionPeekableItem( Workspace workspace, ProjectId projectId, SymbolKey symbolKey, IPeekResultFactory peekResultFactory, IMetadataAsSourceFileService metadataAsSourceService, IGlobalOptionService globalOptions) : base(peekResultFactory) { _workspace = workspace; _projectId = projectId; _symbolKey = symbolKey; _metadataAsSourceFileService = metadataAsSourceService; _globalOptions = globalOptions; } public override IEnumerable<IPeekRelationship> Relationships { get { return SpecializedCollections.SingletonEnumerable(PredefinedPeekRelationships.Definitions); } } public override IPeekResultSource GetOrCreateResultSource(string relationshipName) => new ResultSource(this); private sealed class ResultSource : IPeekResultSource { private readonly DefinitionPeekableItem _peekableItem; public ResultSource(DefinitionPeekableItem peekableItem) => _peekableItem = peekableItem; public void FindResults(string relationshipName, IPeekResultCollection resultCollection, CancellationToken cancellationToken, IFindPeekResultsCallback callback) { if (relationshipName != PredefinedPeekRelationships.Definitions.Name) { return; } // Note: this is called on a background thread, but we must block the thread since the API doesn't support proper asynchrony. var workspace = _peekableItem._workspace; var solution = workspace.CurrentSolution; var project = solution.GetProject(_peekableItem._projectId); var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken); var symbol = _peekableItem._symbolKey.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken).Symbol; if (symbol == null) { callback.ReportFailure(new Exception(EditorFeaturesResources.No_information_found)); return; } var sourceLocations = symbol.Locations.Where(l => l.IsInSource).ToList(); if (!sourceLocations.Any()) { // It's a symbol from metadata, so we want to go produce it from metadata var options = _peekableItem._globalOptions.GetMetadataAsSourceOptions(project.LanguageServices); var declarationFile = _peekableItem._metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, signaturesOnly: false, options, cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken); var peekDisplayInfo = new PeekResultDisplayInfo(declarationFile.DocumentTitle, declarationFile.DocumentTooltip, declarationFile.DocumentTitle, declarationFile.DocumentTooltip); var identifierSpan = declarationFile.IdentifierLocation.GetLineSpan().Span; var entityOfInterestSpan = PeekHelpers.GetEntityOfInterestSpan(symbol, workspace, declarationFile.IdentifierLocation, cancellationToken); resultCollection.Add(PeekHelpers.CreateDocumentPeekResult(declarationFile.FilePath, identifierSpan, entityOfInterestSpan, peekDisplayInfo, _peekableItem.PeekResultFactory, isReadOnly: true)); } var processedSourceLocations = 0; foreach (var declaration in sourceLocations) { var declarationLocation = declaration.GetMappedLineSpan(); var entityOfInterestSpan = PeekHelpers.GetEntityOfInterestSpan(symbol, workspace, declaration, cancellationToken); resultCollection.Add(PeekHelpers.CreateDocumentPeekResult(declarationLocation.Path, declarationLocation.Span, entityOfInterestSpan, _peekableItem.PeekResultFactory)); callback.ReportProgress(100 * ++processedSourceLocations / sourceLocations.Count); } } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/Core/Portable/Workspace/Host/DocumentService/IDocumentOperationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 { /// <summary> /// TODO: Merge into <see cref="DocumentPropertiesService"/>. /// Used by Razor via IVT. /// </summary> internal interface IDocumentOperationService : IDocumentService { /// <summary> /// document version of <see cref="Workspace.CanApplyChange(ApplyChangesKind)"/> /// </summary> bool CanApplyChange { get; } /// <summary> /// indicates whether this document supports diagnostics or not /// </summary> bool SupportDiagnostics { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Host { /// <summary> /// TODO: Merge into <see cref="DocumentPropertiesService"/>. /// Used by Razor via IVT. /// </summary> internal interface IDocumentOperationService : IDocumentService { /// <summary> /// document version of <see cref="Workspace.CanApplyChange(ApplyChangesKind)"/> /// </summary> bool CanApplyChange { get; } /// <summary> /// indicates whether this document supports diagnostics or not /// </summary> bool SupportDiagnostics { get; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Portable/Binding/MethodTypeParametersBinder.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.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A MethodTypeParametersBinder provides the context for looking up type parameters on a method. ''' It is split out since binding of type in the parameters and return value need to happen with a context ''' that includes the type parameters, but we don't have a fully complete method symbol yet. ''' </summary> Friend NotInheritable Class MethodTypeParametersBinder Inherits Binder Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Public Sub New(containingBinder As Binder, typeParameters As ImmutableArray(Of TypeParameterSymbol)) MyBase.New(containingBinder) _typeParameters = typeParameters End Sub ''' <summary> ''' Looks up the name in the type parameters ''' a) type parameters in this type (but not outer or base types) ''' Returns all members of that name, or empty list if none. ''' </summary> Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult, name As String, arity As Integer, options As LookupOptions, originalBinder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) ' type parameters can only be accessed with arity 0 ' Since there are typically just one or two type parameters, using a dictionary/ILookup would be overkill. For i = 0 To _typeParameters.Length - 1 Dim tp = _typeParameters(i) If IdentifierComparison.Equals(tp.Name, name) Then lookupResult.SetFrom(CheckViability(tp, arity, options, Nothing, useSiteInfo)) End If Next End Sub Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) ' UNDONE: check options to see if type parameters should be found. For Each typeParameter In _typeParameters If originalBinder.CanAddLookupSymbolInfo(typeParameter, options, nameSet, Nothing) Then nameSet.AddSymbol(typeParameter, typeParameter.Name, 0) End If Next End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A MethodTypeParametersBinder provides the context for looking up type parameters on a method. ''' It is split out since binding of type in the parameters and return value need to happen with a context ''' that includes the type parameters, but we don't have a fully complete method symbol yet. ''' </summary> Friend NotInheritable Class MethodTypeParametersBinder Inherits Binder Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Public Sub New(containingBinder As Binder, typeParameters As ImmutableArray(Of TypeParameterSymbol)) MyBase.New(containingBinder) _typeParameters = typeParameters End Sub ''' <summary> ''' Looks up the name in the type parameters ''' a) type parameters in this type (but not outer or base types) ''' Returns all members of that name, or empty list if none. ''' </summary> Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult, name As String, arity As Integer, options As LookupOptions, originalBinder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) ' type parameters can only be accessed with arity 0 ' Since there are typically just one or two type parameters, using a dictionary/ILookup would be overkill. For i = 0 To _typeParameters.Length - 1 Dim tp = _typeParameters(i) If IdentifierComparison.Equals(tp.Name, name) Then lookupResult.SetFrom(CheckViability(tp, arity, options, Nothing, useSiteInfo)) End If Next End Sub Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) ' UNDONE: check options to see if type parameters should be found. For Each typeParameter In _typeParameters If originalBinder.CanAddLookupSymbolInfo(typeParameter, options, nameSet, Nothing) Then nameSet.AddSymbol(typeParameter, typeParameter.Name, 0) End If Next End Sub End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Test/Semantic/Semantics/SyncLockTests.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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class SyncLockTests Inherits FlowTestBase #Region "ControlFlowPass and DataflowAnalysis" <Fact()> Public Sub SyncLockInSelect() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="SyncLockInSelect"> <file name="a.vb"> Option Infer On Imports System Class Program Shared Sub Main() Select "" Case "a" [| SyncLock New Object() GoTo lab1 End SyncLock |] End Select lab1: End Sub End Class </file> </compilation>) Dim analysisControlflow = analysis.Item1 Dim analysisDataflow = analysis.Item2 Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.WrittenOutside)) Assert.Equal(0, analysisControlflow.EntryPoints.Count()) Assert.Equal(1, analysisControlflow.ExitPoints.Count()) End Sub <Fact()> Public Sub UnreachableCode() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="UnreachableCode"> <file name="a.vb"> Option Infer On Imports System Class Program Shared Sub Main() [|Dim x1 As Object SyncLock x1 Return End SyncLock|] System.Threading.Monitor.Exit(x1) End Sub End Class </file> </compilation>) Dim analysisControlflow = analysis.Item1 Dim analysisDataflow = analysis.Item2 Assert.Equal("x1", GetSymbolNamesJoined(analysisDataflow.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsOut)) Assert.Equal("x1", GetSymbolNamesJoined(analysisDataflow.ReadInside)) Assert.Equal("x1", GetSymbolNamesJoined(analysisDataflow.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.WrittenOutside)) Assert.Equal(0, analysisControlflow.EntryPoints.Count()) Assert.Equal(1, analysisControlflow.ExitPoints.Count()) End Sub <Fact()> Public Sub AssignmentInSyncLock() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="AssignmentInSyncLock"> <file name="a.vb"> Option Infer On Imports System Class Program Shared Sub Main() Dim myLock As Object [|SyncLock Nothing myLock = New Object() End SyncLock|] System.Console.WriteLine(myLock) End Sub End Class </file> </compilation>) Dim analysisControlflow = analysis.Item1 Dim analysisDataflow = analysis.Item2 Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.VariablesDeclared)) Assert.Equal("myLock", GetSymbolNamesJoined(analysisDataflow.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsIn)) Assert.Equal("myLock", GetSymbolNamesJoined(analysisDataflow.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.ReadInside)) Assert.Equal("myLock", GetSymbolNamesJoined(analysisDataflow.ReadOutside)) Assert.Equal("myLock", GetSymbolNamesJoined(analysisDataflow.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.WrittenOutside)) Assert.Equal(0, analysisControlflow.EntryPoints.Count()) Assert.Equal(0, analysisControlflow.ExitPoints.Count()) End Sub <Fact()> Public Sub SyncLock_AssignmentInInLambda() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="SyncLock_AssignmentInInLambda"> <file name="a.vb"> Option Infer On Imports System Class Program Shared Sub Main() Dim myLock As Object [| SyncLock Sub() myLock = New Object() End Sub End SyncLock|] System.Console.WriteLine(myLock) End Sub End Class </file> </compilation>) Dim analysisControlflow = analysis.Item1 Dim analysisDataflow = analysis.Item2 Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsIn)) Assert.Equal("myLock", GetSymbolNamesJoined(analysisDataflow.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.ReadInside)) Assert.Equal("myLock", GetSymbolNamesJoined(analysisDataflow.ReadOutside)) Assert.Equal("myLock", GetSymbolNamesJoined(analysisDataflow.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.WrittenOutside)) Assert.Equal(0, analysisControlflow.EntryPoints.Count()) Assert.Equal(0, analysisControlflow.ExitPoints.Count()) End Sub <Fact()> Public Sub NestedSyncLock() Dim analysisDataflow = CompileAndAnalyzeDataFlow( <compilation name="NestedSyncLock"> <file name="a.vb"> Public Class Program Public Sub goo() Dim syncroot As Object = New Object SyncLock syncroot [|SyncLock syncroot.ToString() GoTo lab1 syncroot = Nothing End SyncLock|] lab1: End SyncLock System.Threading.Monitor.Enter(syncroot) End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.AlwaysAssigned)) Assert.Equal("syncroot", GetSymbolNamesJoined(analysisDataflow.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsOut)) Assert.Equal("syncroot", GetSymbolNamesJoined(analysisDataflow.ReadInside)) Assert.Equal("syncroot", GetSymbolNamesJoined(analysisDataflow.ReadOutside)) Assert.Equal("syncroot", GetSymbolNamesJoined(analysisDataflow.WrittenInside)) Assert.Equal("Me, syncroot", GetSymbolNamesJoined(analysisDataflow.WrittenOutside)) End Sub <Fact()> Public Sub DataflowOfInnerStatement() Dim analysisDataflow = CompileAndAnalyzeDataFlow( <compilation name="DataflowOfInnerStatement"> <file name="a.vb"> Public Class Program Public Sub goo() Dim syncroot As Object = New Object SyncLock syncroot.ToString() [|Dim x As Integer Return|] End SyncLock System.Threading.Monitor.Enter(syncroot) End Sub End Class </file> </compilation>) Assert.Equal("x", GetSymbolNamesJoined(analysisDataflow.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.ReadInside)) Assert.Equal("syncroot", GetSymbolNamesJoined(analysisDataflow.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.WrittenInside)) Assert.Equal("Me, syncroot", GetSymbolNamesJoined(analysisDataflow.WrittenOutside)) End Sub #End Region #Region "Semantic API" <WorkItem(545364, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545364")> <Fact()> Public Sub SyncLockLambda() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SyncLockLambda"> <file name="a.vb"> Option Infer On Imports System Class Program Shared Sub Main() Dim myLock As Object SyncLock Sub() myLock = New Object() End Sub End SyncLock End Sub End Class </file> </compilation>) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.Null(semanticSummary.Type) Assert.Equal(TypeKind.Delegate, semanticSummary.ConvertedType.TypeKind) Assert.Equal("Sub <generated method>()", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(ConversionKind.Widening Or ConversionKind.Lambda, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub ()", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(True, semanticSummary.Symbol.IsLambdaMethod) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub SyncLockQuery() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="SyncLockQuery"> <file name="a.vb"> Option Strict On Imports System.Linq Class Program Shared Sub Main() SyncLock From w In From x In New Integer() {1, 2, 3} From y In New Char() {"a"c, "b"c} Let bOdd = (x And 1) = 1 Where bOdd Where y > "a"c Let z = x.ToString() &amp; y.ToString() End SyncLock End Sub End Class </file> </compilation>, {SystemCoreRef}) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.NotNull(semanticSummary.Type) Assert.NotNull(semanticSummary.ConvertedType) Assert.True(semanticSummary.Type.IsReferenceType) Assert.Equal("System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As Integer, Key y As Char, Key bOdd As Boolean, Key z As String>)", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub SyncLockGenericType() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="SyncLockGenericType"> <file name="a.vb"> Option Infer ON Class Program Private Shared Sub Goo(Of T As D)(x As T) SyncLock x End SyncLock End Sub End Class Class D End Class </file> </compilation>) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.Equal("T", semanticSummary.Type.ToDisplayString()) Assert.True(semanticSummary.ConvertedType.IsReferenceType) Assert.Equal("T", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("x As T", semanticSummary.Symbol.ToDisplayString()) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub SyncLockAnonymous() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="SyncLockAnonymous"> <file name="a.vb"> Module M1 Sub Main() SyncLock New With {Key .p1 = 10.0} End SyncLock End Sub End Module </file> </compilation>) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.True(semanticSummary.Type.IsReferenceType) Assert.Equal("<anonymous type: Key p1 As Double>", semanticSummary.Type.ToDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.True(semanticSummary.ConvertedType.IsReferenceType) Assert.Equal("<anonymous type: Key p1 As Double>", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Public Sub New(p1 As Double)", semanticSummary.Symbol.ToDisplayString()) End Sub <Fact()> Public Sub SyncLockCreateObject() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="SyncLockCreateObject"> <file name="a.vb"> Module M1 Sub Main() SyncLock New object() End SyncLock End Sub End Module </file> </compilation>) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.True(semanticSummary.Type.IsReferenceType) Assert.Equal("Object", semanticSummary.Type.ToDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Dim symbol = compilation.GetTypeByMetadataName("System.Object") Assert.Equal(symbol, semanticSummary.Type) Assert.True(semanticSummary.ConvertedType.IsReferenceType) Assert.Equal("Object", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Public Overloads Sub New()", semanticSummary.Symbol.ToDisplayString()) End Sub <Fact()> Public Sub SimpleSyncLockNothing() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="SimpleSyncLockNothing"> <file name="a.vb"> Option Strict ON Imports System Class Program Shared Sub Main() SyncLock Nothing Exit Sub End SyncLock End Sub End Class </file> </compilation>) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.Null(semanticSummary.Type) Assert.Equal("Object", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Dim symbol = compilation.GetTypeByMetadataName("System.Object") Assert.Equal(symbol, semanticSummary.ConvertedType) Assert.Equal(ConversionKind.WideningNothingLiteral, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) End Sub <Fact()> Public Sub SimpleSyncLockDelegate() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="SimpleSyncLockDelegate"> <file name="a.vb"> Delegate Sub D(p1 As Integer) Class Program Public Shared Sub Main(args As String()) SyncLock New D(AddressOf PM) End SyncLock End Sub Private Shared Sub PM(p1 As Integer) End Sub End Class </file> </compilation>) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.True(semanticSummary.Type.IsReferenceType) Assert.Equal("D", semanticSummary.Type.ToDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.Type.TypeKind) Dim symbol = compilation.GetTypeByMetadataName("D") Assert.Equal(symbol, semanticSummary.Type) Assert.True(semanticSummary.ConvertedType.IsReferenceType) Assert.Equal("D", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.Type.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) End Sub <Fact()> Public Sub SyncLockMe() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="SyncLockMe"> <file name="a.vb"> Class Program Sub goo() SyncLock Me End SyncLock End Sub End Class </file> </compilation>) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.True(semanticSummary.Type.IsReferenceType) Assert.Equal("Program", semanticSummary.Type.ToDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Dim symbol = compilation.GetTypeByMetadataName("Program") Assert.Equal(symbol, semanticSummary.Type) Assert.True(semanticSummary.ConvertedType.IsReferenceType) Assert.Equal("Program", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Me As Program", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticSummary.Symbol.Kind) End Sub #End Region #Region "Help Method" Private Function GetExpressionFromSyncLock(Compilation As VisualBasicCompilation, Optional which As Integer = 1) As ExpressionSyntax Dim tree = Compilation.SyntaxTrees.[Single]() Dim model = Compilation.GetSemanticModel(tree) Dim SyncLockBlock = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of SyncLockStatementSyntax)().ToList() Return SyncLockBlock(which - 1).Expression End Function #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class SyncLockTests Inherits FlowTestBase #Region "ControlFlowPass and DataflowAnalysis" <Fact()> Public Sub SyncLockInSelect() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="SyncLockInSelect"> <file name="a.vb"> Option Infer On Imports System Class Program Shared Sub Main() Select "" Case "a" [| SyncLock New Object() GoTo lab1 End SyncLock |] End Select lab1: End Sub End Class </file> </compilation>) Dim analysisControlflow = analysis.Item1 Dim analysisDataflow = analysis.Item2 Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.WrittenOutside)) Assert.Equal(0, analysisControlflow.EntryPoints.Count()) Assert.Equal(1, analysisControlflow.ExitPoints.Count()) End Sub <Fact()> Public Sub UnreachableCode() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="UnreachableCode"> <file name="a.vb"> Option Infer On Imports System Class Program Shared Sub Main() [|Dim x1 As Object SyncLock x1 Return End SyncLock|] System.Threading.Monitor.Exit(x1) End Sub End Class </file> </compilation>) Dim analysisControlflow = analysis.Item1 Dim analysisDataflow = analysis.Item2 Assert.Equal("x1", GetSymbolNamesJoined(analysisDataflow.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsOut)) Assert.Equal("x1", GetSymbolNamesJoined(analysisDataflow.ReadInside)) Assert.Equal("x1", GetSymbolNamesJoined(analysisDataflow.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.WrittenOutside)) Assert.Equal(0, analysisControlflow.EntryPoints.Count()) Assert.Equal(1, analysisControlflow.ExitPoints.Count()) End Sub <Fact()> Public Sub AssignmentInSyncLock() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="AssignmentInSyncLock"> <file name="a.vb"> Option Infer On Imports System Class Program Shared Sub Main() Dim myLock As Object [|SyncLock Nothing myLock = New Object() End SyncLock|] System.Console.WriteLine(myLock) End Sub End Class </file> </compilation>) Dim analysisControlflow = analysis.Item1 Dim analysisDataflow = analysis.Item2 Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.VariablesDeclared)) Assert.Equal("myLock", GetSymbolNamesJoined(analysisDataflow.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsIn)) Assert.Equal("myLock", GetSymbolNamesJoined(analysisDataflow.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.ReadInside)) Assert.Equal("myLock", GetSymbolNamesJoined(analysisDataflow.ReadOutside)) Assert.Equal("myLock", GetSymbolNamesJoined(analysisDataflow.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.WrittenOutside)) Assert.Equal(0, analysisControlflow.EntryPoints.Count()) Assert.Equal(0, analysisControlflow.ExitPoints.Count()) End Sub <Fact()> Public Sub SyncLock_AssignmentInInLambda() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="SyncLock_AssignmentInInLambda"> <file name="a.vb"> Option Infer On Imports System Class Program Shared Sub Main() Dim myLock As Object [| SyncLock Sub() myLock = New Object() End Sub End SyncLock|] System.Console.WriteLine(myLock) End Sub End Class </file> </compilation>) Dim analysisControlflow = analysis.Item1 Dim analysisDataflow = analysis.Item2 Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsIn)) Assert.Equal("myLock", GetSymbolNamesJoined(analysisDataflow.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.ReadInside)) Assert.Equal("myLock", GetSymbolNamesJoined(analysisDataflow.ReadOutside)) Assert.Equal("myLock", GetSymbolNamesJoined(analysisDataflow.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.WrittenOutside)) Assert.Equal(0, analysisControlflow.EntryPoints.Count()) Assert.Equal(0, analysisControlflow.ExitPoints.Count()) End Sub <Fact()> Public Sub NestedSyncLock() Dim analysisDataflow = CompileAndAnalyzeDataFlow( <compilation name="NestedSyncLock"> <file name="a.vb"> Public Class Program Public Sub goo() Dim syncroot As Object = New Object SyncLock syncroot [|SyncLock syncroot.ToString() GoTo lab1 syncroot = Nothing End SyncLock|] lab1: End SyncLock System.Threading.Monitor.Enter(syncroot) End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.AlwaysAssigned)) Assert.Equal("syncroot", GetSymbolNamesJoined(analysisDataflow.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsOut)) Assert.Equal("syncroot", GetSymbolNamesJoined(analysisDataflow.ReadInside)) Assert.Equal("syncroot", GetSymbolNamesJoined(analysisDataflow.ReadOutside)) Assert.Equal("syncroot", GetSymbolNamesJoined(analysisDataflow.WrittenInside)) Assert.Equal("Me, syncroot", GetSymbolNamesJoined(analysisDataflow.WrittenOutside)) End Sub <Fact()> Public Sub DataflowOfInnerStatement() Dim analysisDataflow = CompileAndAnalyzeDataFlow( <compilation name="DataflowOfInnerStatement"> <file name="a.vb"> Public Class Program Public Sub goo() Dim syncroot As Object = New Object SyncLock syncroot.ToString() [|Dim x As Integer Return|] End SyncLock System.Threading.Monitor.Enter(syncroot) End Sub End Class </file> </compilation>) Assert.Equal("x", GetSymbolNamesJoined(analysisDataflow.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.ReadInside)) Assert.Equal("syncroot", GetSymbolNamesJoined(analysisDataflow.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisDataflow.WrittenInside)) Assert.Equal("Me, syncroot", GetSymbolNamesJoined(analysisDataflow.WrittenOutside)) End Sub #End Region #Region "Semantic API" <WorkItem(545364, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545364")> <Fact()> Public Sub SyncLockLambda() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SyncLockLambda"> <file name="a.vb"> Option Infer On Imports System Class Program Shared Sub Main() Dim myLock As Object SyncLock Sub() myLock = New Object() End Sub End SyncLock End Sub End Class </file> </compilation>) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.Null(semanticSummary.Type) Assert.Equal(TypeKind.Delegate, semanticSummary.ConvertedType.TypeKind) Assert.Equal("Sub <generated method>()", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(ConversionKind.Widening Or ConversionKind.Lambda, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub ()", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(True, semanticSummary.Symbol.IsLambdaMethod) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub SyncLockQuery() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="SyncLockQuery"> <file name="a.vb"> Option Strict On Imports System.Linq Class Program Shared Sub Main() SyncLock From w In From x In New Integer() {1, 2, 3} From y In New Char() {"a"c, "b"c} Let bOdd = (x And 1) = 1 Where bOdd Where y > "a"c Let z = x.ToString() &amp; y.ToString() End SyncLock End Sub End Class </file> </compilation>, {SystemCoreRef}) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.NotNull(semanticSummary.Type) Assert.NotNull(semanticSummary.ConvertedType) Assert.True(semanticSummary.Type.IsReferenceType) Assert.Equal("System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As Integer, Key y As Char, Key bOdd As Boolean, Key z As String>)", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub SyncLockGenericType() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="SyncLockGenericType"> <file name="a.vb"> Option Infer ON Class Program Private Shared Sub Goo(Of T As D)(x As T) SyncLock x End SyncLock End Sub End Class Class D End Class </file> </compilation>) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.Equal("T", semanticSummary.Type.ToDisplayString()) Assert.True(semanticSummary.ConvertedType.IsReferenceType) Assert.Equal("T", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("x As T", semanticSummary.Symbol.ToDisplayString()) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub SyncLockAnonymous() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="SyncLockAnonymous"> <file name="a.vb"> Module M1 Sub Main() SyncLock New With {Key .p1 = 10.0} End SyncLock End Sub End Module </file> </compilation>) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.True(semanticSummary.Type.IsReferenceType) Assert.Equal("<anonymous type: Key p1 As Double>", semanticSummary.Type.ToDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.True(semanticSummary.ConvertedType.IsReferenceType) Assert.Equal("<anonymous type: Key p1 As Double>", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Public Sub New(p1 As Double)", semanticSummary.Symbol.ToDisplayString()) End Sub <Fact()> Public Sub SyncLockCreateObject() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="SyncLockCreateObject"> <file name="a.vb"> Module M1 Sub Main() SyncLock New object() End SyncLock End Sub End Module </file> </compilation>) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.True(semanticSummary.Type.IsReferenceType) Assert.Equal("Object", semanticSummary.Type.ToDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Dim symbol = compilation.GetTypeByMetadataName("System.Object") Assert.Equal(symbol, semanticSummary.Type) Assert.True(semanticSummary.ConvertedType.IsReferenceType) Assert.Equal("Object", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Public Overloads Sub New()", semanticSummary.Symbol.ToDisplayString()) End Sub <Fact()> Public Sub SimpleSyncLockNothing() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="SimpleSyncLockNothing"> <file name="a.vb"> Option Strict ON Imports System Class Program Shared Sub Main() SyncLock Nothing Exit Sub End SyncLock End Sub End Class </file> </compilation>) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.Null(semanticSummary.Type) Assert.Equal("Object", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Dim symbol = compilation.GetTypeByMetadataName("System.Object") Assert.Equal(symbol, semanticSummary.ConvertedType) Assert.Equal(ConversionKind.WideningNothingLiteral, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) End Sub <Fact()> Public Sub SimpleSyncLockDelegate() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="SimpleSyncLockDelegate"> <file name="a.vb"> Delegate Sub D(p1 As Integer) Class Program Public Shared Sub Main(args As String()) SyncLock New D(AddressOf PM) End SyncLock End Sub Private Shared Sub PM(p1 As Integer) End Sub End Class </file> </compilation>) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.True(semanticSummary.Type.IsReferenceType) Assert.Equal("D", semanticSummary.Type.ToDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.Type.TypeKind) Dim symbol = compilation.GetTypeByMetadataName("D") Assert.Equal(symbol, semanticSummary.Type) Assert.True(semanticSummary.ConvertedType.IsReferenceType) Assert.Equal("D", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.Type.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) End Sub <Fact()> Public Sub SyncLockMe() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="SyncLockMe"> <file name="a.vb"> Class Program Sub goo() SyncLock Me End SyncLock End Sub End Class </file> </compilation>) Dim expression = GetExpressionFromSyncLock(compilation) Dim semanticSummary = GetSemanticInfoSummary(compilation, expression) Assert.True(semanticSummary.Type.IsReferenceType) Assert.Equal("Program", semanticSummary.Type.ToDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Dim symbol = compilation.GetTypeByMetadataName("Program") Assert.Equal(symbol, semanticSummary.Type) Assert.True(semanticSummary.ConvertedType.IsReferenceType) Assert.Equal("Program", semanticSummary.ConvertedType.ToDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Me As Program", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticSummary.Symbol.Kind) End Sub #End Region #Region "Help Method" Private Function GetExpressionFromSyncLock(Compilation As VisualBasicCompilation, Optional which As Integer = 1) As ExpressionSyntax Dim tree = Compilation.SyntaxTrees.[Single]() Dim model = Compilation.GetSemanticModel(tree) Dim SyncLockBlock = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of SyncLockStatementSyntax)().ToList() Return SyncLockBlock(which - 1).Expression End Function #End Region End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.NonNegativeIntValueSetFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private sealed class NonNegativeIntValueSetFactory : IValueSetFactory<int> { public static readonly NonNegativeIntValueSetFactory Instance = new NonNegativeIntValueSetFactory(); private NonNegativeIntValueSetFactory() { } private readonly IValueSetFactory<int> _underlying = NumericValueSetFactory<int, NonNegativeIntTC>.Instance; public IValueSet AllValues => NumericValueSet<int, NonNegativeIntTC>.AllValues; public IValueSet NoValues => NumericValueSet<int, NonNegativeIntTC>.NoValues; public IValueSet<int> Related(BinaryOperatorKind relation, int value) { switch (relation) { case LessThan: if (value <= 0) return NumericValueSet<int, NonNegativeIntTC>.NoValues; return new NumericValueSet<int, NonNegativeIntTC>(0, value - 1); case LessThanOrEqual: if (value < 0) return NumericValueSet<int, NonNegativeIntTC>.NoValues; return new NumericValueSet<int, NonNegativeIntTC>(0, value); case GreaterThan: if (value == int.MaxValue) return NumericValueSet<int, NonNegativeIntTC>.NoValues; return new NumericValueSet<int, NonNegativeIntTC>(Math.Max(0, value + 1), int.MaxValue); case GreaterThanOrEqual: return new NumericValueSet<int, NonNegativeIntTC>(Math.Max(0, value), int.MaxValue); case Equal: if (value < 0) return NumericValueSet<int, NonNegativeIntTC>.NoValues; return new NumericValueSet<int, NonNegativeIntTC>(value, value); default: throw ExceptionUtilities.UnexpectedValue(relation); } } IValueSet IValueSetFactory.Random(int expectedSize, Random random) => _underlying.Random(expectedSize, random); ConstantValue IValueSetFactory.RandomValue(Random random) => _underlying.RandomValue(random); IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) => value.IsBad ? AllValues : Related(relation, default(NonNegativeIntTC).FromConstantValue(value)); bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right) => _underlying.Related(relation, left, right); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private sealed class NonNegativeIntValueSetFactory : IValueSetFactory<int> { public static readonly NonNegativeIntValueSetFactory Instance = new NonNegativeIntValueSetFactory(); private NonNegativeIntValueSetFactory() { } private readonly IValueSetFactory<int> _underlying = NumericValueSetFactory<int, NonNegativeIntTC>.Instance; public IValueSet AllValues => NumericValueSet<int, NonNegativeIntTC>.AllValues; public IValueSet NoValues => NumericValueSet<int, NonNegativeIntTC>.NoValues; public IValueSet<int> Related(BinaryOperatorKind relation, int value) { switch (relation) { case LessThan: if (value <= 0) return NumericValueSet<int, NonNegativeIntTC>.NoValues; return new NumericValueSet<int, NonNegativeIntTC>(0, value - 1); case LessThanOrEqual: if (value < 0) return NumericValueSet<int, NonNegativeIntTC>.NoValues; return new NumericValueSet<int, NonNegativeIntTC>(0, value); case GreaterThan: if (value == int.MaxValue) return NumericValueSet<int, NonNegativeIntTC>.NoValues; return new NumericValueSet<int, NonNegativeIntTC>(Math.Max(0, value + 1), int.MaxValue); case GreaterThanOrEqual: return new NumericValueSet<int, NonNegativeIntTC>(Math.Max(0, value), int.MaxValue); case Equal: if (value < 0) return NumericValueSet<int, NonNegativeIntTC>.NoValues; return new NumericValueSet<int, NonNegativeIntTC>(value, value); default: throw ExceptionUtilities.UnexpectedValue(relation); } } IValueSet IValueSetFactory.Random(int expectedSize, Random random) => _underlying.Random(expectedSize, random); ConstantValue IValueSetFactory.RandomValue(Random random) => _underlying.RandomValue(random); IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) => value.IsBad ? AllValues : Related(relation, default(NonNegativeIntTC).FromConstantValue(value)); bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right) => _underlying.Related(relation, left, right); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEFieldSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.CSharp.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// The class to represent all fields imported from a PE/module. /// </summary> internal sealed class PEFieldSymbol : FieldSymbol { private struct PackedFlags { // Layout: // |........................|qq|rr|v|fffff| // // f = FlowAnalysisAnnotations. 5 bits (4 value bits + 1 completion bit). // v = IsVolatile 1 bit // r = RefKind 2 bits // q = Required members. 2 bits (1 value bit + 1 completion bit). private const int HasDisallowNullAttribute = 0x1 << 0; private const int HasAllowNullAttribute = 0x1 << 1; private const int HasMaybeNullAttribute = 0x1 << 2; private const int HasNotNullAttribute = 0x1 << 3; private const int FlowAnalysisAnnotationsCompletionBit = 0x1 << 4; private const int IsVolatileBit = 0x1 << 5; private const int RefKindOffset = 6; private const int RefKindMask = 0x3; private const int HasRequiredMemberAttribute = 0x1 << 8; private const int RequiredMemberCompletionBit = 0x1 << 9; private int _bits; public bool SetFlowAnalysisAnnotations(FlowAnalysisAnnotations value) { Debug.Assert((value & ~(FlowAnalysisAnnotations.DisallowNull | FlowAnalysisAnnotations.AllowNull | FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull)) == 0); int bitsToSet = FlowAnalysisAnnotationsCompletionBit; if ((value & FlowAnalysisAnnotations.DisallowNull) != 0) bitsToSet |= PackedFlags.HasDisallowNullAttribute; if ((value & FlowAnalysisAnnotations.AllowNull) != 0) bitsToSet |= PackedFlags.HasAllowNullAttribute; if ((value & FlowAnalysisAnnotations.MaybeNull) != 0) bitsToSet |= PackedFlags.HasMaybeNullAttribute; if ((value & FlowAnalysisAnnotations.NotNull) != 0) bitsToSet |= PackedFlags.HasNotNullAttribute; return ThreadSafeFlagOperations.Set(ref _bits, bitsToSet); } public bool TryGetFlowAnalysisAnnotations(out FlowAnalysisAnnotations value) { int theBits = _bits; // Read this.bits once to ensure the consistency of the value and completion flags. value = FlowAnalysisAnnotations.None; if ((theBits & PackedFlags.HasDisallowNullAttribute) != 0) value |= FlowAnalysisAnnotations.DisallowNull; if ((theBits & PackedFlags.HasAllowNullAttribute) != 0) value |= FlowAnalysisAnnotations.AllowNull; if ((theBits & PackedFlags.HasMaybeNullAttribute) != 0) value |= FlowAnalysisAnnotations.MaybeNull; if ((theBits & PackedFlags.HasNotNullAttribute) != 0) value |= FlowAnalysisAnnotations.NotNull; var result = (theBits & FlowAnalysisAnnotationsCompletionBit) != 0; Debug.Assert(value == 0 || result); return result; } public void SetIsVolatile(bool isVolatile) { if (isVolatile) ThreadSafeFlagOperations.Set(ref _bits, IsVolatileBit); Debug.Assert(IsVolatile == isVolatile); } public bool IsVolatile => (_bits & IsVolatileBit) != 0; public void SetRefKind(RefKind refKind) { int bits = ((int)refKind & RefKindMask) << RefKindOffset; if (bits != 0) ThreadSafeFlagOperations.Set(ref _bits, bits); Debug.Assert(RefKind == refKind); } public RefKind RefKind => (RefKind)((_bits >> RefKindOffset) & RefKindMask); public bool SetHasRequiredMemberAttribute(bool isRequired) { int bitsToSet = RequiredMemberCompletionBit | (isRequired ? HasRequiredMemberAttribute : 0); return ThreadSafeFlagOperations.Set(ref _bits, bitsToSet); } public bool TryGetHasRequiredMemberAttribute(out bool hasRequiredMemberAttribute) { if ((_bits & RequiredMemberCompletionBit) != 0) { hasRequiredMemberAttribute = (_bits & HasRequiredMemberAttribute) != 0; return true; } hasRequiredMemberAttribute = false; return false; } } private readonly FieldDefinitionHandle _handle; private readonly string _name; private readonly FieldAttributes _flags; private readonly PENamedTypeSymbol _containingType; private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes; private ConstantValue _lazyConstantValue = Microsoft.CodeAnalysis.ConstantValue.Unset; // Indicates an uninitialized ConstantValue private Tuple<CultureInfo, string> _lazyDocComment; private CachedUseSiteInfo<AssemblySymbol> _lazyCachedUseSiteInfo = CachedUseSiteInfo<AssemblySymbol>.Uninitialized; private ObsoleteAttributeData _lazyObsoleteAttributeData = ObsoleteAttributeData.Uninitialized; private TypeWithAnnotations.Boxed _lazyType; private int _lazyFixedSize; private NamedTypeSymbol _lazyFixedImplementationType; private PEEventSymbol _associatedEventOpt; private PackedFlags _packedFlags; private ImmutableArray<CustomModifier> _lazyRefCustomModifiers; internal PEFieldSymbol( PEModuleSymbol moduleSymbol, PENamedTypeSymbol containingType, FieldDefinitionHandle fieldDef) { Debug.Assert((object)moduleSymbol != null); Debug.Assert((object)containingType != null); Debug.Assert(!fieldDef.IsNil); _handle = fieldDef; _containingType = containingType; _packedFlags = new PackedFlags(); try { moduleSymbol.Module.GetFieldDefPropsOrThrow(fieldDef, out _name, out _flags); } catch (BadImageFormatException) { if ((object)_name == null) { _name = String.Empty; } _lazyCachedUseSiteInfo.Initialize(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this)); } } public override Symbol ContainingSymbol { get { return _containingType; } } public override NamedTypeSymbol ContainingType { get { return _containingType; } } public override string Name { get { return _name; } } public override int MetadataToken { get { return MetadataTokens.GetToken(_handle); } } internal FieldAttributes Flags { get { return _flags; } } internal override bool HasSpecialName { get { return (_flags & FieldAttributes.SpecialName) != 0; } } internal override bool HasRuntimeSpecialName { get { return (_flags & FieldAttributes.RTSpecialName) != 0; } } internal override bool IsNotSerialized { get { return (_flags & FieldAttributes.NotSerialized) != 0; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { // the compiler doesn't need full marshalling information, just the unmanaged type or descriptor return null; } } internal override bool IsMarshalledExplicitly { get { return ((_flags & FieldAttributes.HasFieldMarshal) != 0); } } internal override UnmanagedType MarshallingType { get { if ((_flags & FieldAttributes.HasFieldMarshal) == 0) { return 0; } return _containingType.ContainingPEModule.Module.GetMarshallingType(_handle); } } internal override ImmutableArray<byte> MarshallingDescriptor { get { if ((_flags & FieldAttributes.HasFieldMarshal) == 0) { return default(ImmutableArray<byte>); } return _containingType.ContainingPEModule.Module.GetMarshallingDescriptor(_handle); } } internal override int? TypeLayoutOffset { get { return _containingType.ContainingPEModule.Module.GetFieldOffset(_handle); } } internal FieldDefinitionHandle Handle { get { return _handle; } } /// <summary> /// Mark this field as the backing field of a field-like event. /// The caller will also ensure that it is excluded from the member list of /// the containing type (as it would be in source). /// </summary> internal void SetAssociatedEvent(PEEventSymbol eventSymbol) { Debug.Assert((object)eventSymbol != null); Debug.Assert(TypeSymbol.Equals(eventSymbol.ContainingType, _containingType, TypeCompareKind.ConsiderEverything2)); // This should always be true in valid metadata - there should only // be one event with a given name in a given type. if ((object)_associatedEventOpt == null) { // No locking required since this method will only be called by the thread that created // the field symbol (and will be called before the field symbol is added to the containing // type members and available to other threads). _associatedEventOpt = eventSymbol; } } private void EnsureSignatureIsLoaded() { if (_lazyType == null) { var moduleSymbol = _containingType.ContainingPEModule; FieldInfo<TypeSymbol> fieldInfo = new MetadataDecoder(moduleSymbol, _containingType).DecodeFieldSignature(_handle); TypeSymbol typeSymbol = fieldInfo.Type; ImmutableArray<CustomModifier> customModifiersArray = CSharpCustomModifier.Convert(fieldInfo.CustomModifiers); typeSymbol = DynamicTypeDecoder.TransformType(typeSymbol, customModifiersArray.Length, _handle, moduleSymbol); typeSymbol = NativeIntegerTypeDecoder.TransformType(typeSymbol, _handle, moduleSymbol, _containingType); // We start without annotations var type = TypeWithAnnotations.Create(typeSymbol, customModifiers: customModifiersArray); // Decode nullable before tuple types to avoid converting between // NamedTypeSymbol and TupleTypeSymbol unnecessarily. type = NullableTypeDecoder.TransformType(type, _handle, moduleSymbol, accessSymbol: this, nullableContext: _containingType); type = TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, _handle, moduleSymbol); RefKind refKind = fieldInfo.IsByRef ? moduleSymbol.Module.HasIsReadOnlyAttribute(_handle) ? RefKind.RefReadOnly : RefKind.Ref : RefKind.None; _packedFlags.SetRefKind(refKind); _packedFlags.SetIsVolatile(customModifiersArray.Any(static m => !m.IsOptional && ((CSharpCustomModifier)m).ModifierSymbol.SpecialType == SpecialType.System_Runtime_CompilerServices_IsVolatile)); TypeSymbol fixedElementType; int fixedSize; if (customModifiersArray.IsEmpty && IsFixedBuffer(out fixedSize, out fixedElementType)) { _lazyFixedSize = fixedSize; _lazyFixedImplementationType = type.Type as NamedTypeSymbol; type = TypeWithAnnotations.Create(new PointerTypeSymbol(TypeWithAnnotations.Create(fixedElementType))); } ImmutableInterlocked.InterlockedInitialize(ref _lazyRefCustomModifiers, CSharpCustomModifier.Convert(fieldInfo.RefCustomModifiers)); Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(type), null); } } private bool IsFixedBuffer(out int fixedSize, out TypeSymbol fixedElementType) { fixedSize = 0; fixedElementType = null; string elementTypeName; int bufferSize; PEModuleSymbol containingPEModule = this.ContainingPEModule; if (containingPEModule.Module.HasFixedBufferAttribute(_handle, out elementTypeName, out bufferSize)) { var decoder = new MetadataDecoder(containingPEModule); var elementType = decoder.GetTypeSymbolForSerializedType(elementTypeName); if (elementType.FixedBufferElementSizeInBytes() != 0) { fixedSize = bufferSize; fixedElementType = elementType; return true; } } return false; } private PEModuleSymbol ContainingPEModule { get { return ((PENamespaceSymbol)ContainingNamespace).ContainingPEModule; } } public override RefKind RefKind { get { EnsureSignatureIsLoaded(); return _packedFlags.RefKind; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { EnsureSignatureIsLoaded(); return _lazyRefCustomModifiers; } } internal override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound) { EnsureSignatureIsLoaded(); return _lazyType.Value; } public override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { FlowAnalysisAnnotations value; if (!_packedFlags.TryGetFlowAnalysisAnnotations(out value)) { value = DecodeFlowAnalysisAttributes(_containingType.ContainingPEModule.Module, _handle); _packedFlags.SetFlowAnalysisAnnotations(value); } return value; } } private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(PEModule module, FieldDefinitionHandle handle) { FlowAnalysisAnnotations annotations = FlowAnalysisAnnotations.None; if (module.HasAttribute(handle, AttributeDescription.AllowNullAttribute)) annotations |= FlowAnalysisAnnotations.AllowNull; if (module.HasAttribute(handle, AttributeDescription.DisallowNullAttribute)) annotations |= FlowAnalysisAnnotations.DisallowNull; if (module.HasAttribute(handle, AttributeDescription.MaybeNullAttribute)) annotations |= FlowAnalysisAnnotations.MaybeNull; if (module.HasAttribute(handle, AttributeDescription.NotNullAttribute)) annotations |= FlowAnalysisAnnotations.NotNull; return annotations; } public override bool IsFixedSizeBuffer { get { EnsureSignatureIsLoaded(); return (object)_lazyFixedImplementationType != null; } } public override int FixedSize { get { EnsureSignatureIsLoaded(); return _lazyFixedSize; } } internal override NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) { EnsureSignatureIsLoaded(); return _lazyFixedImplementationType; } public override Symbol AssociatedSymbol { get { return _associatedEventOpt; } } public override bool IsReadOnly { get { return (_flags & FieldAttributes.InitOnly) != 0; } } public override bool IsVolatile { get { EnsureSignatureIsLoaded(); return _packedFlags.IsVolatile; } } public override bool IsConst { get { return (_flags & FieldAttributes.Literal) != 0 || GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false) != null; } } internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) { if (_lazyConstantValue == Microsoft.CodeAnalysis.ConstantValue.Unset) { ConstantValue value = null; if ((_flags & FieldAttributes.Literal) != 0) { value = _containingType.ContainingPEModule.Module.GetConstantFieldValue(_handle); } // If this is a Decimal, the constant value may come from DecimalConstantAttribute if (this.Type.SpecialType == SpecialType.System_Decimal) { ConstantValue defaultValue; if (_containingType.ContainingPEModule.Module.HasDecimalConstantAttribute(Handle, out defaultValue)) { value = defaultValue; } } Interlocked.CompareExchange( ref _lazyConstantValue, value, Microsoft.CodeAnalysis.ConstantValue.Unset); } return _lazyConstantValue; } public override ImmutableArray<Location> Locations { get { return _containingType.ContainingPEModule.MetadataLocation.Cast<MetadataLocation, Location>(); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } public override Accessibility DeclaredAccessibility { get { var access = Accessibility.Private; switch (_flags & FieldAttributes.FieldAccessMask) { case FieldAttributes.Assembly: access = Accessibility.Internal; break; case FieldAttributes.FamORAssem: access = Accessibility.ProtectedOrInternal; break; case FieldAttributes.FamANDAssem: access = Accessibility.ProtectedAndInternal; break; case FieldAttributes.Private: case FieldAttributes.PrivateScope: access = Accessibility.Private; break; case FieldAttributes.Public: access = Accessibility.Public; break; case FieldAttributes.Family: access = Accessibility.Protected; break; default: access = Accessibility.Private; break; } return access; } } public override bool IsStatic { get { return (_flags & FieldAttributes.Static) != 0; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { if (_lazyCustomAttributes.IsDefault) { var containingPEModuleSymbol = (PEModuleSymbol)this.ContainingModule; if (FilterOutDecimalConstantAttribute()) { // filter out DecimalConstantAttribute var attributes = containingPEModuleSymbol.GetCustomAttributesForToken( _handle, out _, AttributeDescription.DecimalConstantAttribute); ImmutableInterlocked.InterlockedInitialize(ref _lazyCustomAttributes, attributes); } else { containingPEModuleSymbol.LoadCustomAttributes(_handle, ref _lazyCustomAttributes); } } return _lazyCustomAttributes; } private bool FilterOutDecimalConstantAttribute() { ConstantValue value; return this.Type.SpecialType == SpecialType.System_Decimal && (object)(value = GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false)) != null && value.Discriminator == ConstantValueTypeDiscriminator.Decimal; } internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { foreach (CSharpAttributeData attribute in GetAttributes()) { yield return attribute; } // Yield hidden attributes last, order might be important. if (FilterOutDecimalConstantAttribute()) { var containingPEModuleSymbol = _containingType.ContainingPEModule; yield return new PEAttributeData(containingPEModuleSymbol, containingPEModuleSymbol.Module.FindLastTargetAttribute(_handle, AttributeDescription.DecimalConstantAttribute).Handle); } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return PEDocumentationCommentUtils.GetDocumentationComment(this, _containingType.ContainingPEModule, preferredCulture, cancellationToken, ref _lazyDocComment); } internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { AssemblySymbol primaryDependency = PrimaryDependency; if (!_lazyCachedUseSiteInfo.IsInitialized) { UseSiteInfo<AssemblySymbol> result = new UseSiteInfo<AssemblySymbol>(primaryDependency); CalculateUseSiteDiagnostic(ref result); if (RefKind != RefKind.None && (IsFixedSizeBuffer || Type.IsRefLikeType == true)) { MergeUseSiteInfo(ref result, new UseSiteInfo<AssemblySymbol>(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this))); } deriveCompilerFeatureRequiredUseSiteInfo(ref result); _lazyCachedUseSiteInfo.Initialize(primaryDependency, result); } return _lazyCachedUseSiteInfo.ToUseSiteInfo(primaryDependency); void deriveCompilerFeatureRequiredUseSiteInfo(ref UseSiteInfo<AssemblySymbol> result) { var containingType = (PENamedTypeSymbol)ContainingType; PEModuleSymbol containingPEModule = _containingType.ContainingPEModule; var diag = PEUtilities.DeriveCompilerFeatureRequiredAttributeDiagnostic( this, containingPEModule, Handle, allowedFeatures: CompilerFeatureRequiredFeatures.None, new MetadataDecoder(containingPEModule, containingType)); diag ??= containingType.GetCompilerFeatureRequiredDiagnostic(); if (diag != null) { result = new UseSiteInfo<AssemblySymbol>(diag); } } } internal override ObsoleteAttributeData ObsoleteAttributeData { get { ObsoleteAttributeHelpers.InitializeObsoleteDataFromMetadata(ref _lazyObsoleteAttributeData, _handle, (PEModuleSymbol)(this.ContainingModule), ignoreByRefLikeMarker: false, ignoreRequiredMemberMarker: false); return _lazyObsoleteAttributeData; } } internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness { get { return null; } } internal override bool IsRequired { get { if (!_packedFlags.TryGetHasRequiredMemberAttribute(out bool hasRequiredMemberAttribute)) { hasRequiredMemberAttribute = ContainingPEModule.Module.HasAttribute(_handle, AttributeDescription.RequiredMemberAttribute); _packedFlags.SetHasRequiredMemberAttribute(hasRequiredMemberAttribute); } return hasRequiredMemberAttribute; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.CSharp.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// The class to represent all fields imported from a PE/module. /// </summary> internal sealed class PEFieldSymbol : FieldSymbol { private struct PackedFlags { // Layout: // |........................|qq|rr|v|fffff| // // f = FlowAnalysisAnnotations. 5 bits (4 value bits + 1 completion bit). // v = IsVolatile 1 bit // r = RefKind 2 bits // q = Required members. 2 bits (1 value bit + 1 completion bit). private const int HasDisallowNullAttribute = 0x1 << 0; private const int HasAllowNullAttribute = 0x1 << 1; private const int HasMaybeNullAttribute = 0x1 << 2; private const int HasNotNullAttribute = 0x1 << 3; private const int FlowAnalysisAnnotationsCompletionBit = 0x1 << 4; private const int IsVolatileBit = 0x1 << 5; private const int RefKindOffset = 6; private const int RefKindMask = 0x3; private const int HasRequiredMemberAttribute = 0x1 << 8; private const int RequiredMemberCompletionBit = 0x1 << 9; private int _bits; public bool SetFlowAnalysisAnnotations(FlowAnalysisAnnotations value) { Debug.Assert((value & ~(FlowAnalysisAnnotations.DisallowNull | FlowAnalysisAnnotations.AllowNull | FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull)) == 0); int bitsToSet = FlowAnalysisAnnotationsCompletionBit; if ((value & FlowAnalysisAnnotations.DisallowNull) != 0) bitsToSet |= PackedFlags.HasDisallowNullAttribute; if ((value & FlowAnalysisAnnotations.AllowNull) != 0) bitsToSet |= PackedFlags.HasAllowNullAttribute; if ((value & FlowAnalysisAnnotations.MaybeNull) != 0) bitsToSet |= PackedFlags.HasMaybeNullAttribute; if ((value & FlowAnalysisAnnotations.NotNull) != 0) bitsToSet |= PackedFlags.HasNotNullAttribute; return ThreadSafeFlagOperations.Set(ref _bits, bitsToSet); } public bool TryGetFlowAnalysisAnnotations(out FlowAnalysisAnnotations value) { int theBits = _bits; // Read this.bits once to ensure the consistency of the value and completion flags. value = FlowAnalysisAnnotations.None; if ((theBits & PackedFlags.HasDisallowNullAttribute) != 0) value |= FlowAnalysisAnnotations.DisallowNull; if ((theBits & PackedFlags.HasAllowNullAttribute) != 0) value |= FlowAnalysisAnnotations.AllowNull; if ((theBits & PackedFlags.HasMaybeNullAttribute) != 0) value |= FlowAnalysisAnnotations.MaybeNull; if ((theBits & PackedFlags.HasNotNullAttribute) != 0) value |= FlowAnalysisAnnotations.NotNull; var result = (theBits & FlowAnalysisAnnotationsCompletionBit) != 0; Debug.Assert(value == 0 || result); return result; } public void SetIsVolatile(bool isVolatile) { if (isVolatile) ThreadSafeFlagOperations.Set(ref _bits, IsVolatileBit); Debug.Assert(IsVolatile == isVolatile); } public bool IsVolatile => (_bits & IsVolatileBit) != 0; public void SetRefKind(RefKind refKind) { int bits = ((int)refKind & RefKindMask) << RefKindOffset; if (bits != 0) ThreadSafeFlagOperations.Set(ref _bits, bits); Debug.Assert(RefKind == refKind); } public RefKind RefKind => (RefKind)((_bits >> RefKindOffset) & RefKindMask); public bool SetHasRequiredMemberAttribute(bool isRequired) { int bitsToSet = RequiredMemberCompletionBit | (isRequired ? HasRequiredMemberAttribute : 0); return ThreadSafeFlagOperations.Set(ref _bits, bitsToSet); } public bool TryGetHasRequiredMemberAttribute(out bool hasRequiredMemberAttribute) { if ((_bits & RequiredMemberCompletionBit) != 0) { hasRequiredMemberAttribute = (_bits & HasRequiredMemberAttribute) != 0; return true; } hasRequiredMemberAttribute = false; return false; } } private readonly FieldDefinitionHandle _handle; private readonly string _name; private readonly FieldAttributes _flags; private readonly PENamedTypeSymbol _containingType; private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes; private ConstantValue _lazyConstantValue = Microsoft.CodeAnalysis.ConstantValue.Unset; // Indicates an uninitialized ConstantValue private Tuple<CultureInfo, string> _lazyDocComment; private CachedUseSiteInfo<AssemblySymbol> _lazyCachedUseSiteInfo = CachedUseSiteInfo<AssemblySymbol>.Uninitialized; private ObsoleteAttributeData _lazyObsoleteAttributeData = ObsoleteAttributeData.Uninitialized; private TypeWithAnnotations.Boxed _lazyType; private int _lazyFixedSize; private NamedTypeSymbol _lazyFixedImplementationType; private PEEventSymbol _associatedEventOpt; private PackedFlags _packedFlags; private ImmutableArray<CustomModifier> _lazyRefCustomModifiers; internal PEFieldSymbol( PEModuleSymbol moduleSymbol, PENamedTypeSymbol containingType, FieldDefinitionHandle fieldDef) { Debug.Assert((object)moduleSymbol != null); Debug.Assert((object)containingType != null); Debug.Assert(!fieldDef.IsNil); _handle = fieldDef; _containingType = containingType; _packedFlags = new PackedFlags(); try { moduleSymbol.Module.GetFieldDefPropsOrThrow(fieldDef, out _name, out _flags); } catch (BadImageFormatException) { if ((object)_name == null) { _name = String.Empty; } _lazyCachedUseSiteInfo.Initialize(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this)); } } public override Symbol ContainingSymbol { get { return _containingType; } } public override NamedTypeSymbol ContainingType { get { return _containingType; } } public override string Name { get { return _name; } } public override int MetadataToken { get { return MetadataTokens.GetToken(_handle); } } internal FieldAttributes Flags { get { return _flags; } } internal override bool HasSpecialName { get { return (_flags & FieldAttributes.SpecialName) != 0; } } internal override bool HasRuntimeSpecialName { get { return (_flags & FieldAttributes.RTSpecialName) != 0; } } internal override bool IsNotSerialized { get { return (_flags & FieldAttributes.NotSerialized) != 0; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { // the compiler doesn't need full marshalling information, just the unmanaged type or descriptor return null; } } internal override bool IsMarshalledExplicitly { get { return ((_flags & FieldAttributes.HasFieldMarshal) != 0); } } internal override UnmanagedType MarshallingType { get { if ((_flags & FieldAttributes.HasFieldMarshal) == 0) { return 0; } return _containingType.ContainingPEModule.Module.GetMarshallingType(_handle); } } internal override ImmutableArray<byte> MarshallingDescriptor { get { if ((_flags & FieldAttributes.HasFieldMarshal) == 0) { return default(ImmutableArray<byte>); } return _containingType.ContainingPEModule.Module.GetMarshallingDescriptor(_handle); } } internal override int? TypeLayoutOffset { get { return _containingType.ContainingPEModule.Module.GetFieldOffset(_handle); } } internal FieldDefinitionHandle Handle { get { return _handle; } } /// <summary> /// Mark this field as the backing field of a field-like event. /// The caller will also ensure that it is excluded from the member list of /// the containing type (as it would be in source). /// </summary> internal void SetAssociatedEvent(PEEventSymbol eventSymbol) { Debug.Assert((object)eventSymbol != null); Debug.Assert(TypeSymbol.Equals(eventSymbol.ContainingType, _containingType, TypeCompareKind.ConsiderEverything2)); // This should always be true in valid metadata - there should only // be one event with a given name in a given type. if ((object)_associatedEventOpt == null) { // No locking required since this method will only be called by the thread that created // the field symbol (and will be called before the field symbol is added to the containing // type members and available to other threads). _associatedEventOpt = eventSymbol; } } private void EnsureSignatureIsLoaded() { if (_lazyType == null) { var moduleSymbol = _containingType.ContainingPEModule; FieldInfo<TypeSymbol> fieldInfo = new MetadataDecoder(moduleSymbol, _containingType).DecodeFieldSignature(_handle); TypeSymbol typeSymbol = fieldInfo.Type; ImmutableArray<CustomModifier> customModifiersArray = CSharpCustomModifier.Convert(fieldInfo.CustomModifiers); typeSymbol = DynamicTypeDecoder.TransformType(typeSymbol, customModifiersArray.Length, _handle, moduleSymbol); typeSymbol = NativeIntegerTypeDecoder.TransformType(typeSymbol, _handle, moduleSymbol, _containingType); // We start without annotations var type = TypeWithAnnotations.Create(typeSymbol, customModifiers: customModifiersArray); // Decode nullable before tuple types to avoid converting between // NamedTypeSymbol and TupleTypeSymbol unnecessarily. type = NullableTypeDecoder.TransformType(type, _handle, moduleSymbol, accessSymbol: this, nullableContext: _containingType); type = TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, _handle, moduleSymbol); RefKind refKind = fieldInfo.IsByRef ? moduleSymbol.Module.HasIsReadOnlyAttribute(_handle) ? RefKind.RefReadOnly : RefKind.Ref : RefKind.None; _packedFlags.SetRefKind(refKind); _packedFlags.SetIsVolatile(customModifiersArray.Any(static m => !m.IsOptional && ((CSharpCustomModifier)m).ModifierSymbol.SpecialType == SpecialType.System_Runtime_CompilerServices_IsVolatile)); TypeSymbol fixedElementType; int fixedSize; if (customModifiersArray.IsEmpty && IsFixedBuffer(out fixedSize, out fixedElementType)) { _lazyFixedSize = fixedSize; _lazyFixedImplementationType = type.Type as NamedTypeSymbol; type = TypeWithAnnotations.Create(new PointerTypeSymbol(TypeWithAnnotations.Create(fixedElementType))); } ImmutableInterlocked.InterlockedInitialize(ref _lazyRefCustomModifiers, CSharpCustomModifier.Convert(fieldInfo.RefCustomModifiers)); Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(type), null); } } private bool IsFixedBuffer(out int fixedSize, out TypeSymbol fixedElementType) { fixedSize = 0; fixedElementType = null; string elementTypeName; int bufferSize; PEModuleSymbol containingPEModule = this.ContainingPEModule; if (containingPEModule.Module.HasFixedBufferAttribute(_handle, out elementTypeName, out bufferSize)) { var decoder = new MetadataDecoder(containingPEModule); var elementType = decoder.GetTypeSymbolForSerializedType(elementTypeName); if (elementType.FixedBufferElementSizeInBytes() != 0) { fixedSize = bufferSize; fixedElementType = elementType; return true; } } return false; } private PEModuleSymbol ContainingPEModule { get { return ((PENamespaceSymbol)ContainingNamespace).ContainingPEModule; } } public override RefKind RefKind { get { EnsureSignatureIsLoaded(); return _packedFlags.RefKind; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { EnsureSignatureIsLoaded(); return _lazyRefCustomModifiers; } } internal override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound) { EnsureSignatureIsLoaded(); return _lazyType.Value; } public override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { FlowAnalysisAnnotations value; if (!_packedFlags.TryGetFlowAnalysisAnnotations(out value)) { value = DecodeFlowAnalysisAttributes(_containingType.ContainingPEModule.Module, _handle); _packedFlags.SetFlowAnalysisAnnotations(value); } return value; } } private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(PEModule module, FieldDefinitionHandle handle) { FlowAnalysisAnnotations annotations = FlowAnalysisAnnotations.None; if (module.HasAttribute(handle, AttributeDescription.AllowNullAttribute)) annotations |= FlowAnalysisAnnotations.AllowNull; if (module.HasAttribute(handle, AttributeDescription.DisallowNullAttribute)) annotations |= FlowAnalysisAnnotations.DisallowNull; if (module.HasAttribute(handle, AttributeDescription.MaybeNullAttribute)) annotations |= FlowAnalysisAnnotations.MaybeNull; if (module.HasAttribute(handle, AttributeDescription.NotNullAttribute)) annotations |= FlowAnalysisAnnotations.NotNull; return annotations; } public override bool IsFixedSizeBuffer { get { EnsureSignatureIsLoaded(); return (object)_lazyFixedImplementationType != null; } } public override int FixedSize { get { EnsureSignatureIsLoaded(); return _lazyFixedSize; } } internal override NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) { EnsureSignatureIsLoaded(); return _lazyFixedImplementationType; } public override Symbol AssociatedSymbol { get { return _associatedEventOpt; } } public override bool IsReadOnly { get { return (_flags & FieldAttributes.InitOnly) != 0; } } public override bool IsVolatile { get { EnsureSignatureIsLoaded(); return _packedFlags.IsVolatile; } } public override bool IsConst { get { return (_flags & FieldAttributes.Literal) != 0 || GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false) != null; } } internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) { if (_lazyConstantValue == Microsoft.CodeAnalysis.ConstantValue.Unset) { ConstantValue value = null; if ((_flags & FieldAttributes.Literal) != 0) { value = _containingType.ContainingPEModule.Module.GetConstantFieldValue(_handle); } // If this is a Decimal, the constant value may come from DecimalConstantAttribute if (this.Type.SpecialType == SpecialType.System_Decimal) { ConstantValue defaultValue; if (_containingType.ContainingPEModule.Module.HasDecimalConstantAttribute(Handle, out defaultValue)) { value = defaultValue; } } Interlocked.CompareExchange( ref _lazyConstantValue, value, Microsoft.CodeAnalysis.ConstantValue.Unset); } return _lazyConstantValue; } public override ImmutableArray<Location> Locations { get { return _containingType.ContainingPEModule.MetadataLocation.Cast<MetadataLocation, Location>(); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } public override Accessibility DeclaredAccessibility { get { var access = Accessibility.Private; switch (_flags & FieldAttributes.FieldAccessMask) { case FieldAttributes.Assembly: access = Accessibility.Internal; break; case FieldAttributes.FamORAssem: access = Accessibility.ProtectedOrInternal; break; case FieldAttributes.FamANDAssem: access = Accessibility.ProtectedAndInternal; break; case FieldAttributes.Private: case FieldAttributes.PrivateScope: access = Accessibility.Private; break; case FieldAttributes.Public: access = Accessibility.Public; break; case FieldAttributes.Family: access = Accessibility.Protected; break; default: access = Accessibility.Private; break; } return access; } } public override bool IsStatic { get { return (_flags & FieldAttributes.Static) != 0; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { if (_lazyCustomAttributes.IsDefault) { var containingPEModuleSymbol = (PEModuleSymbol)this.ContainingModule; if (FilterOutDecimalConstantAttribute()) { // filter out DecimalConstantAttribute var attributes = containingPEModuleSymbol.GetCustomAttributesForToken( _handle, out _, AttributeDescription.DecimalConstantAttribute); ImmutableInterlocked.InterlockedInitialize(ref _lazyCustomAttributes, attributes); } else { containingPEModuleSymbol.LoadCustomAttributes(_handle, ref _lazyCustomAttributes); } } return _lazyCustomAttributes; } private bool FilterOutDecimalConstantAttribute() { ConstantValue value; return this.Type.SpecialType == SpecialType.System_Decimal && (object)(value = GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false)) != null && value.Discriminator == ConstantValueTypeDiscriminator.Decimal; } internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { foreach (CSharpAttributeData attribute in GetAttributes()) { yield return attribute; } // Yield hidden attributes last, order might be important. if (FilterOutDecimalConstantAttribute()) { var containingPEModuleSymbol = _containingType.ContainingPEModule; yield return new PEAttributeData(containingPEModuleSymbol, containingPEModuleSymbol.Module.FindLastTargetAttribute(_handle, AttributeDescription.DecimalConstantAttribute).Handle); } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return PEDocumentationCommentUtils.GetDocumentationComment(this, _containingType.ContainingPEModule, preferredCulture, cancellationToken, ref _lazyDocComment); } internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { AssemblySymbol primaryDependency = PrimaryDependency; if (!_lazyCachedUseSiteInfo.IsInitialized) { UseSiteInfo<AssemblySymbol> result = new UseSiteInfo<AssemblySymbol>(primaryDependency); CalculateUseSiteDiagnostic(ref result); if (RefKind != RefKind.None && (IsFixedSizeBuffer || Type.IsRefLikeType == true)) { MergeUseSiteInfo(ref result, new UseSiteInfo<AssemblySymbol>(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this))); } deriveCompilerFeatureRequiredUseSiteInfo(ref result); _lazyCachedUseSiteInfo.Initialize(primaryDependency, result); } return _lazyCachedUseSiteInfo.ToUseSiteInfo(primaryDependency); void deriveCompilerFeatureRequiredUseSiteInfo(ref UseSiteInfo<AssemblySymbol> result) { var containingType = (PENamedTypeSymbol)ContainingType; PEModuleSymbol containingPEModule = _containingType.ContainingPEModule; var diag = PEUtilities.DeriveCompilerFeatureRequiredAttributeDiagnostic( this, containingPEModule, Handle, allowedFeatures: CompilerFeatureRequiredFeatures.None, new MetadataDecoder(containingPEModule, containingType)); diag ??= containingType.GetCompilerFeatureRequiredDiagnostic(); if (diag != null) { result = new UseSiteInfo<AssemblySymbol>(diag); } } } internal override ObsoleteAttributeData ObsoleteAttributeData { get { ObsoleteAttributeHelpers.InitializeObsoleteDataFromMetadata(ref _lazyObsoleteAttributeData, _handle, (PEModuleSymbol)(this.ContainingModule), ignoreByRefLikeMarker: false, ignoreRequiredMemberMarker: false); return _lazyObsoleteAttributeData; } } internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness { get { return null; } } internal override bool IsRequired { get { if (!_packedFlags.TryGetHasRequiredMemberAttribute(out bool hasRequiredMemberAttribute)) { hasRequiredMemberAttribute = ContainingPEModule.Module.HasAttribute(_handle, AttributeDescription.RequiredMemberAttribute); _packedFlags.SetHasRequiredMemberAttribute(hasRequiredMemberAttribute); } return hasRequiredMemberAttribute; } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/CSharp/Impl/Options/Formatting/FormattingOptionPageControl.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Formatting; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; using System.Runtime.CompilerServices; // 🐉 The XAML markup compiler does not recognize InternalsVisibleTo. However, since it allows type // forwarding, we use TypeForwardedTo to make CodeStyleNoticeTextBlock appear to the markup compiler // as an internal type in the current assembly instead of an internal type in one of the referenced // assemblies. [assembly: TypeForwardedTo(typeof(CodeStyleNoticeTextBlock))] namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { /// <summary> /// Interaction logic for FormattingOptionPageControl.xaml /// </summary> internal partial class FormattingOptionPageControl : AbstractOptionPageControl { public FormattingOptionPageControl(OptionStore optionStore) : base(optionStore) { InitializeComponent(); FormatWhenTypingCheckBox.Content = CSharpVSResources.Automatically_format_when_typing; FormatOnSemicolonCheckBox.Content = CSharpVSResources.Automatically_format_statement_on_semicolon; FormatOnCloseBraceCheckBox.Content = CSharpVSResources.Automatically_format_block_on_close_brace; FormatOnReturnCheckBox.Content = CSharpVSResources.Automatically_format_on_return; FormatOnPasteCheckBox.Content = CSharpVSResources.Automatically_format_on_paste; BindToOption(FormatWhenTypingCheckBox, AutoFormattingOptionsStorage.FormatOnTyping, LanguageNames.CSharp); BindToOption(FormatOnCloseBraceCheckBox, AutoFormattingOptionsStorage.FormatOnCloseBrace, LanguageNames.CSharp); BindToOption(FormatOnSemicolonCheckBox, AutoFormattingOptionsStorage.FormatOnSemicolon, LanguageNames.CSharp); BindToOption(FormatOnReturnCheckBox, AutoFormattingOptionsStorage.FormatOnReturn, LanguageNames.CSharp); BindToOption(FormatOnPasteCheckBox, FormattingOptionsMetadata.FormatOnPaste, LanguageNames.CSharp); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; using Microsoft.CodeAnalysis.Formatting; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; using System.Runtime.CompilerServices; // 🐉 The XAML markup compiler does not recognize InternalsVisibleTo. However, since it allows type // forwarding, we use TypeForwardedTo to make CodeStyleNoticeTextBlock appear to the markup compiler // as an internal type in the current assembly instead of an internal type in one of the referenced // assemblies. [assembly: TypeForwardedTo(typeof(CodeStyleNoticeTextBlock))] namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { /// <summary> /// Interaction logic for FormattingOptionPageControl.xaml /// </summary> internal partial class FormattingOptionPageControl : AbstractOptionPageControl { public FormattingOptionPageControl(OptionStore optionStore) : base(optionStore) { InitializeComponent(); FormatWhenTypingCheckBox.Content = CSharpVSResources.Automatically_format_when_typing; FormatOnSemicolonCheckBox.Content = CSharpVSResources.Automatically_format_statement_on_semicolon; FormatOnCloseBraceCheckBox.Content = CSharpVSResources.Automatically_format_block_on_close_brace; FormatOnReturnCheckBox.Content = CSharpVSResources.Automatically_format_on_return; FormatOnPasteCheckBox.Content = CSharpVSResources.Automatically_format_on_paste; BindToOption(FormatWhenTypingCheckBox, AutoFormattingOptionsStorage.FormatOnTyping, LanguageNames.CSharp); BindToOption(FormatOnCloseBraceCheckBox, AutoFormattingOptionsStorage.FormatOnCloseBrace, LanguageNames.CSharp); BindToOption(FormatOnSemicolonCheckBox, AutoFormattingOptionsStorage.FormatOnSemicolon, LanguageNames.CSharp); BindToOption(FormatOnReturnCheckBox, AutoFormattingOptionsStorage.FormatOnReturn, LanguageNames.CSharp); BindToOption(FormatOnPasteCheckBox, FormattingOptionsMetadata.FormatOnPaste, LanguageNames.CSharp); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageService.Factory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { internal partial class TemporaryStorageService { [ExportWorkspaceServiceFactory(typeof(ITemporaryStorageService), ServiceLayer.Default), Shared] internal partial class Factory : IWorkspaceServiceFactory { private readonly IWorkspaceThreadingService? _workspaceThreadingService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory( [Import(AllowDefault = true)] IWorkspaceThreadingService? workspaceThreadingService) { _workspaceThreadingService = workspaceThreadingService; } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { var textFactory = workspaceServices.GetRequiredService<ITextFactoryService>(); // MemoryMapped files which are used by the TemporaryStorageService are present in .NET Framework (including Mono) // and .NET Core Windows. For non-Windows .NET Core scenarios, we can return the TrivialTemporaryStorageService // until https://github.com/dotnet/runtime/issues/30878 is fixed. return PlatformInformation.IsWindows || PlatformInformation.IsRunningOnMono ? new TemporaryStorageService(_workspaceThreadingService, textFactory) : TrivialTemporaryStorageService.Instance; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { internal partial class TemporaryStorageService { [ExportWorkspaceServiceFactory(typeof(ITemporaryStorageService), ServiceLayer.Default), Shared] internal partial class Factory : IWorkspaceServiceFactory { private readonly IWorkspaceThreadingService? _workspaceThreadingService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory( [Import(AllowDefault = true)] IWorkspaceThreadingService? workspaceThreadingService) { _workspaceThreadingService = workspaceThreadingService; } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { var textFactory = workspaceServices.GetRequiredService<ITextFactoryService>(); // MemoryMapped files which are used by the TemporaryStorageService are present in .NET Framework (including Mono) // and .NET Core Windows. For non-Windows .NET Core scenarios, we can return the TrivialTemporaryStorageService // until https://github.com/dotnet/runtime/issues/30878 is fixed. return PlatformInformation.IsWindows || PlatformInformation.IsRunningOnMono ? new TemporaryStorageService(_workspaceThreadingService, textFactory) : TrivialTemporaryStorageService.Instance; } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/Core/Portable/OrganizeImports/OrganizeImportsOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; namespace Microsoft.CodeAnalysis.OrganizeImports; [DataContract] internal readonly record struct OrganizeImportsOptions { [DataMember] public bool PlaceSystemNamespaceFirst { get; init; } = AddImportPlacementOptions.Default.PlaceSystemNamespaceFirst; [DataMember] public bool SeparateImportDirectiveGroups { get; init; } = SyntaxFormattingOptions.CommonOptions.Default.SeparateImportDirectiveGroups; [DataMember] public string NewLine { get; init; } = LineFormattingOptions.Default.NewLine; public OrganizeImportsOptions() { } public static readonly OrganizeImportsOptions Default = new(); } internal interface OrganizeImportsOptionsProvider : OptionsProvider<OrganizeImportsOptions> { } internal static class OrganizeImportsOptionsProviders { public static OrganizeImportsOptions GetOrganizeImportsOptions(this AnalyzerConfigOptions options, OrganizeImportsOptions? fallbackOptions) { fallbackOptions ??= OrganizeImportsOptions.Default; return new() { PlaceSystemNamespaceFirst = options.GetEditorConfigOption(GenerationOptions.PlaceSystemNamespaceFirst, fallbackOptions.Value.PlaceSystemNamespaceFirst), SeparateImportDirectiveGroups = options.GetEditorConfigOption(GenerationOptions.SeparateImportDirectiveGroups, fallbackOptions.Value.SeparateImportDirectiveGroups), NewLine = options.GetEditorConfigOption(FormattingOptions2.NewLine, fallbackOptions.Value.NewLine) }; } public static async ValueTask<OrganizeImportsOptions> GetOrganizeImportsOptionsAsync(this Document document, OrganizeImportsOptions? fallbackOptions, CancellationToken cancellationToken) { var configOptions = await document.GetAnalyzerConfigOptionsAsync(cancellationToken).ConfigureAwait(false); return configOptions.GetOrganizeImportsOptions(fallbackOptions); } public static async ValueTask<OrganizeImportsOptions> GetOrganizeImportsOptionsAsync(this Document document, OrganizeImportsOptionsProvider fallbackOptionsProvider, CancellationToken cancellationToken) => await GetOrganizeImportsOptionsAsync(document, await fallbackOptionsProvider.GetOptionsAsync(document.Project.LanguageServices, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; namespace Microsoft.CodeAnalysis.OrganizeImports; [DataContract] internal readonly record struct OrganizeImportsOptions { [DataMember] public bool PlaceSystemNamespaceFirst { get; init; } = AddImportPlacementOptions.Default.PlaceSystemNamespaceFirst; [DataMember] public bool SeparateImportDirectiveGroups { get; init; } = SyntaxFormattingOptions.CommonOptions.Default.SeparateImportDirectiveGroups; [DataMember] public string NewLine { get; init; } = LineFormattingOptions.Default.NewLine; public OrganizeImportsOptions() { } public static readonly OrganizeImportsOptions Default = new(); } internal interface OrganizeImportsOptionsProvider : OptionsProvider<OrganizeImportsOptions> { } internal static class OrganizeImportsOptionsProviders { public static OrganizeImportsOptions GetOrganizeImportsOptions(this AnalyzerConfigOptions options, OrganizeImportsOptions? fallbackOptions) { fallbackOptions ??= OrganizeImportsOptions.Default; return new() { PlaceSystemNamespaceFirst = options.GetEditorConfigOption(GenerationOptions.PlaceSystemNamespaceFirst, fallbackOptions.Value.PlaceSystemNamespaceFirst), SeparateImportDirectiveGroups = options.GetEditorConfigOption(GenerationOptions.SeparateImportDirectiveGroups, fallbackOptions.Value.SeparateImportDirectiveGroups), NewLine = options.GetEditorConfigOption(FormattingOptions2.NewLine, fallbackOptions.Value.NewLine) }; } public static async ValueTask<OrganizeImportsOptions> GetOrganizeImportsOptionsAsync(this Document document, OrganizeImportsOptions? fallbackOptions, CancellationToken cancellationToken) { var configOptions = await document.GetAnalyzerConfigOptionsAsync(cancellationToken).ConfigureAwait(false); return configOptions.GetOrganizeImportsOptions(fallbackOptions); } public static async ValueTask<OrganizeImportsOptions> GetOrganizeImportsOptionsAsync(this Document document, OrganizeImportsOptionsProvider fallbackOptionsProvider, CancellationToken cancellationToken) => await GetOrganizeImportsOptionsAsync(document, await fallbackOptionsProvider.GetOptionsAsync(document.Project.LanguageServices, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_Try.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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode Debug.Assert(_unstructuredExceptionHandling.Context Is Nothing) Dim rewrittenTryBlock = RewriteTryBlock(node) Dim rewrittenCatchBlocks = VisitList(node.CatchBlocks) Dim rewrittenFinally = RewriteFinallyBlock(node) Dim rewritten As BoundStatement = RewriteTryStatement(node.Syntax, rewrittenTryBlock, rewrittenCatchBlocks, rewrittenFinally, node.ExitLabelOpt) If Me.Instrument(node) Then Dim syntax = TryCast(node.Syntax, TryBlockSyntax) If syntax IsNot Nothing Then rewritten = _instrumenterOpt.InstrumentTryStatement(node, rewritten) End If End If Return rewritten End Function ''' <summary> ''' Is there any code to execute in the given statement that could have side-effects, ''' such as throwing an exception? This implementation is conservative, in the sense ''' that it may return true when the statement actually may have no side effects. ''' </summary> Private Shared Function HasSideEffects(statement As BoundStatement) As Boolean If statement Is Nothing Then Return False End If Select Case statement.Kind Case BoundKind.NoOpStatement Return False Case BoundKind.Block Dim block = DirectCast(statement, BoundBlock) For Each s In block.Statements If HasSideEffects(s) Then Return True End If Next Return False Case BoundKind.SequencePoint Dim sequence = DirectCast(statement, BoundSequencePoint) Return HasSideEffects(sequence.StatementOpt) Case BoundKind.SequencePointWithSpan Dim sequence = DirectCast(statement, BoundSequencePointWithSpan) Return HasSideEffects(sequence.StatementOpt) Case Else Return True End Select End Function Public Function RewriteTryStatement( syntaxNode As SyntaxNode, tryBlock As BoundBlock, catchBlocks As ImmutableArray(Of BoundCatchBlock), finallyBlockOpt As BoundBlock, exitLabelOpt As LabelSymbol ) As BoundStatement If Not Me.OptimizationLevelIsDebug Then ' When optimizing and the try block has no side effects, we can discard the catch blocks. If Not HasSideEffects(tryBlock) Then catchBlocks = ImmutableArray(Of BoundCatchBlock).Empty End If ' A finally block with no side effects can be omitted. If Not HasSideEffects(finallyBlockOpt) Then finallyBlockOpt = Nothing End If If catchBlocks.IsDefaultOrEmpty AndAlso finallyBlockOpt Is Nothing Then If exitLabelOpt Is Nothing Then Return tryBlock Else ' Ensure implicit label statement is materialized Return New BoundStatementList(syntaxNode, ImmutableArray.Create(Of BoundStatement)(tryBlock, New BoundLabelStatement(syntaxNode, exitLabelOpt))) End If End If End If Dim newTry As BoundStatement = New BoundTryStatement(syntaxNode, tryBlock, catchBlocks, finallyBlockOpt, exitLabelOpt) For Each [catch] In catchBlocks ReportErrorsOnCatchBlockHelpers([catch]) Next Return newTry End Function Private Function RewriteFinallyBlock(tryStatement As BoundTryStatement) As BoundBlock Dim node As BoundBlock = tryStatement.FinallyBlockOpt If node Is Nothing Then Return node End If Dim newFinally = DirectCast(Visit(node), BoundBlock) If Instrument(tryStatement) Then Dim syntax = TryCast(node.Syntax, FinallyBlockSyntax) If syntax IsNot Nothing Then newFinally = PrependWithPrologue(newFinally, _instrumenterOpt.CreateFinallyBlockPrologue(tryStatement)) End If End If Return newFinally End Function Private Function RewriteTryBlock(tryStatement As BoundTryStatement) As BoundBlock Dim node As BoundBlock = tryStatement.TryBlock Dim newTry = DirectCast(Visit(node), BoundBlock) If Instrument(tryStatement) Then Dim syntax = TryCast(node.Syntax, TryBlockSyntax) If syntax IsNot Nothing Then newTry = PrependWithPrologue(newTry, _instrumenterOpt.CreateTryBlockPrologue(tryStatement)) End If End If Return newTry End Function Public Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode Dim newExceptionSource = VisitExpressionNode(node.ExceptionSourceOpt) Dim newFilter = VisitExpressionNode(node.ExceptionFilterOpt) Dim newCatchBody As BoundBlock = DirectCast(Visit(node.Body), BoundBlock) If Instrument(node) Then Dim syntax = TryCast(node.Syntax, CatchBlockSyntax) If syntax IsNot Nothing Then If newFilter IsNot Nothing Then ' if we have a filter, we want to stop before the filter expression ' and associate the sequence point with whole Catch statement ' EnC: We need to insert a hidden sequence point to handle function remapping in case ' the containing method is edited while methods invoked in the condition are being executed. newFilter = _instrumenterOpt.InstrumentCatchBlockFilter(node, newFilter, _currentMethodOrLambda) Else newCatchBody = PrependWithPrologue(newCatchBody, _instrumenterOpt.CreateCatchBlockPrologue(node)) End If End If End If Dim errorLineNumber As BoundExpression = Nothing If node.ErrorLineNumberOpt IsNot Nothing Then Debug.Assert(_currentLineTemporary Is Nothing) Debug.Assert((Me._flags And RewritingFlags.AllowCatchWithErrorLineNumberReference) <> 0) errorLineNumber = VisitExpressionNode(node.ErrorLineNumberOpt) ElseIf _currentLineTemporary IsNot Nothing AndAlso _currentMethodOrLambda Is _topMethod Then errorLineNumber = New BoundLocal(node.Syntax, _currentLineTemporary, isLValue:=False, type:=_currentLineTemporary.Type) End If Return node.Update(node.LocalOpt, newExceptionSource, errorLineNumber, newFilter, newCatchBody, node.IsSynthesizedAsyncCatchAll) End Function Private Sub ReportErrorsOnCatchBlockHelpers(node As BoundCatchBlock) ' when starting/finishing any code associated with an exception handler (including exception filters) ' we need to call SetProjectError/ClearProjectError ' NOTE: we do not inject the helper calls via a rewrite. ' SetProjectError is called with implicit argument on the stack and cannot be expressed in the tree. ' ClearProjectError could be added as a rewrite, but for similarity with SetProjectError we will do it in IL gen too. ' we will however check for the presence of the helpers and complain here if we cannot find them. ' TODO: when building VB runtime, this check is unnecessary as we should not emit the helpers. Dim setProjectError As WellKnownMember = If(node.ErrorLineNumberOpt Is Nothing, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32) Dim setProjectErrorMethod As MethodSymbol = DirectCast(Compilation.GetWellKnownTypeMember(setProjectError), MethodSymbol) ReportMissingOrBadRuntimeHelper(node, setProjectError, setProjectErrorMethod) If node.ExceptionFilterOpt Is Nothing OrElse node.ExceptionFilterOpt.Kind <> BoundKind.UnstructuredExceptionHandlingCatchFilter Then Const clearProjectError As WellKnownMember = WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError Dim clearProjectErrorMethod = DirectCast(Compilation.GetWellKnownTypeMember(clearProjectError), MethodSymbol) ReportMissingOrBadRuntimeHelper(node, clearProjectError, clearProjectErrorMethod) End If End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode Debug.Assert(_unstructuredExceptionHandling.Context Is Nothing) Dim rewrittenTryBlock = RewriteTryBlock(node) Dim rewrittenCatchBlocks = VisitList(node.CatchBlocks) Dim rewrittenFinally = RewriteFinallyBlock(node) Dim rewritten As BoundStatement = RewriteTryStatement(node.Syntax, rewrittenTryBlock, rewrittenCatchBlocks, rewrittenFinally, node.ExitLabelOpt) If Me.Instrument(node) Then Dim syntax = TryCast(node.Syntax, TryBlockSyntax) If syntax IsNot Nothing Then rewritten = _instrumenterOpt.InstrumentTryStatement(node, rewritten) End If End If Return rewritten End Function ''' <summary> ''' Is there any code to execute in the given statement that could have side-effects, ''' such as throwing an exception? This implementation is conservative, in the sense ''' that it may return true when the statement actually may have no side effects. ''' </summary> Private Shared Function HasSideEffects(statement As BoundStatement) As Boolean If statement Is Nothing Then Return False End If Select Case statement.Kind Case BoundKind.NoOpStatement Return False Case BoundKind.Block Dim block = DirectCast(statement, BoundBlock) For Each s In block.Statements If HasSideEffects(s) Then Return True End If Next Return False Case BoundKind.SequencePoint Dim sequence = DirectCast(statement, BoundSequencePoint) Return HasSideEffects(sequence.StatementOpt) Case BoundKind.SequencePointWithSpan Dim sequence = DirectCast(statement, BoundSequencePointWithSpan) Return HasSideEffects(sequence.StatementOpt) Case Else Return True End Select End Function Public Function RewriteTryStatement( syntaxNode As SyntaxNode, tryBlock As BoundBlock, catchBlocks As ImmutableArray(Of BoundCatchBlock), finallyBlockOpt As BoundBlock, exitLabelOpt As LabelSymbol ) As BoundStatement If Not Me.OptimizationLevelIsDebug Then ' When optimizing and the try block has no side effects, we can discard the catch blocks. If Not HasSideEffects(tryBlock) Then catchBlocks = ImmutableArray(Of BoundCatchBlock).Empty End If ' A finally block with no side effects can be omitted. If Not HasSideEffects(finallyBlockOpt) Then finallyBlockOpt = Nothing End If If catchBlocks.IsDefaultOrEmpty AndAlso finallyBlockOpt Is Nothing Then If exitLabelOpt Is Nothing Then Return tryBlock Else ' Ensure implicit label statement is materialized Return New BoundStatementList(syntaxNode, ImmutableArray.Create(Of BoundStatement)(tryBlock, New BoundLabelStatement(syntaxNode, exitLabelOpt))) End If End If End If Dim newTry As BoundStatement = New BoundTryStatement(syntaxNode, tryBlock, catchBlocks, finallyBlockOpt, exitLabelOpt) For Each [catch] In catchBlocks ReportErrorsOnCatchBlockHelpers([catch]) Next Return newTry End Function Private Function RewriteFinallyBlock(tryStatement As BoundTryStatement) As BoundBlock Dim node As BoundBlock = tryStatement.FinallyBlockOpt If node Is Nothing Then Return node End If Dim newFinally = DirectCast(Visit(node), BoundBlock) If Instrument(tryStatement) Then Dim syntax = TryCast(node.Syntax, FinallyBlockSyntax) If syntax IsNot Nothing Then newFinally = PrependWithPrologue(newFinally, _instrumenterOpt.CreateFinallyBlockPrologue(tryStatement)) End If End If Return newFinally End Function Private Function RewriteTryBlock(tryStatement As BoundTryStatement) As BoundBlock Dim node As BoundBlock = tryStatement.TryBlock Dim newTry = DirectCast(Visit(node), BoundBlock) If Instrument(tryStatement) Then Dim syntax = TryCast(node.Syntax, TryBlockSyntax) If syntax IsNot Nothing Then newTry = PrependWithPrologue(newTry, _instrumenterOpt.CreateTryBlockPrologue(tryStatement)) End If End If Return newTry End Function Public Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode Dim newExceptionSource = VisitExpressionNode(node.ExceptionSourceOpt) Dim newFilter = VisitExpressionNode(node.ExceptionFilterOpt) Dim newCatchBody As BoundBlock = DirectCast(Visit(node.Body), BoundBlock) If Instrument(node) Then Dim syntax = TryCast(node.Syntax, CatchBlockSyntax) If syntax IsNot Nothing Then If newFilter IsNot Nothing Then ' if we have a filter, we want to stop before the filter expression ' and associate the sequence point with whole Catch statement ' EnC: We need to insert a hidden sequence point to handle function remapping in case ' the containing method is edited while methods invoked in the condition are being executed. newFilter = _instrumenterOpt.InstrumentCatchBlockFilter(node, newFilter, _currentMethodOrLambda) Else newCatchBody = PrependWithPrologue(newCatchBody, _instrumenterOpt.CreateCatchBlockPrologue(node)) End If End If End If Dim errorLineNumber As BoundExpression = Nothing If node.ErrorLineNumberOpt IsNot Nothing Then Debug.Assert(_currentLineTemporary Is Nothing) Debug.Assert((Me._flags And RewritingFlags.AllowCatchWithErrorLineNumberReference) <> 0) errorLineNumber = VisitExpressionNode(node.ErrorLineNumberOpt) ElseIf _currentLineTemporary IsNot Nothing AndAlso _currentMethodOrLambda Is _topMethod Then errorLineNumber = New BoundLocal(node.Syntax, _currentLineTemporary, isLValue:=False, type:=_currentLineTemporary.Type) End If Return node.Update(node.LocalOpt, newExceptionSource, errorLineNumber, newFilter, newCatchBody, node.IsSynthesizedAsyncCatchAll) End Function Private Sub ReportErrorsOnCatchBlockHelpers(node As BoundCatchBlock) ' when starting/finishing any code associated with an exception handler (including exception filters) ' we need to call SetProjectError/ClearProjectError ' NOTE: we do not inject the helper calls via a rewrite. ' SetProjectError is called with implicit argument on the stack and cannot be expressed in the tree. ' ClearProjectError could be added as a rewrite, but for similarity with SetProjectError we will do it in IL gen too. ' we will however check for the presence of the helpers and complain here if we cannot find them. ' TODO: when building VB runtime, this check is unnecessary as we should not emit the helpers. Dim setProjectError As WellKnownMember = If(node.ErrorLineNumberOpt Is Nothing, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32) Dim setProjectErrorMethod As MethodSymbol = DirectCast(Compilation.GetWellKnownTypeMember(setProjectError), MethodSymbol) ReportMissingOrBadRuntimeHelper(node, setProjectError, setProjectErrorMethod) If node.ExceptionFilterOpt Is Nothing OrElse node.ExceptionFilterOpt.Kind <> BoundKind.UnstructuredExceptionHandlingCatchFilter Then Const clearProjectError As WellKnownMember = WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError Dim clearProjectErrorMethod = DirectCast(Compilation.GetWellKnownTypeMember(clearProjectError), MethodSymbol) ReportMissingOrBadRuntimeHelper(node, clearProjectError, clearProjectErrorMethod) End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/Core/Portable/Simplification/Simplifiers/AbstractSimplifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Simplification.Simplifiers { internal abstract class AbstractSimplifier<TSyntax, TSimplifiedSyntax, TSimplifierOptions> where TSyntax : SyntaxNode where TSimplifiedSyntax : SyntaxNode where TSimplifierOptions : SimplifierOptions { public abstract bool TrySimplify( TSyntax syntax, SemanticModel semanticModel, TSimplifierOptions options, out TSimplifiedSyntax replacementNode, out TextSpan issueSpan, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Simplification.Simplifiers { internal abstract class AbstractSimplifier<TSyntax, TSimplifiedSyntax, TSimplifierOptions> where TSyntax : SyntaxNode where TSimplifiedSyntax : SyntaxNode where TSimplifierOptions : SimplifierOptions { public abstract bool TrySimplify( TSyntax syntax, SemanticModel semanticModel, TSimplifierOptions options, out TSimplifiedSyntax replacementNode, out TextSpan issueSpan, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/Core/Portable/CodeFixes/ExportCodeFixProviderAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Use this attribute to declare a <see cref="CodeFixProvider"/> implementation so that it can be discovered by the host. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public sealed class ExportCodeFixProviderAttribute : ExportAttribute { /// <summary> /// Optional name of the <see cref="CodeFixProvider"/>. /// </summary> [DisallowNull] public string? Name { get; set; } /// <summary> /// The source languages this provider can provide fixes for. See <see cref="LanguageNames"/>. /// </summary> public string[] Languages { get; } /// <summary> /// Attribute constructor used to specify automatic application of a code fix provider. /// </summary> /// <param name="firstLanguage">One language to which the code fix provider applies.</param> /// <param name="additionalLanguages">Additional languages to which the code fix provider applies. See <see cref="LanguageNames"/>.</param> public ExportCodeFixProviderAttribute( string firstLanguage, params string[] additionalLanguages) : base(typeof(CodeFixProvider)) { if (additionalLanguages == null) { throw new ArgumentNullException(nameof(additionalLanguages)); } var languages = new string[additionalLanguages.Length + 1]; languages[0] = firstLanguage ?? throw new ArgumentNullException(nameof(firstLanguage)); for (var index = 0; index < additionalLanguages.Length; index++) { languages[index + 1] = additionalLanguages[index]; } this.Languages = languages; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Use this attribute to declare a <see cref="CodeFixProvider"/> implementation so that it can be discovered by the host. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public sealed class ExportCodeFixProviderAttribute : ExportAttribute { /// <summary> /// Optional name of the <see cref="CodeFixProvider"/>. /// </summary> [DisallowNull] public string? Name { get; set; } /// <summary> /// The source languages this provider can provide fixes for. See <see cref="LanguageNames"/>. /// </summary> public string[] Languages { get; } /// <summary> /// Attribute constructor used to specify automatic application of a code fix provider. /// </summary> /// <param name="firstLanguage">One language to which the code fix provider applies.</param> /// <param name="additionalLanguages">Additional languages to which the code fix provider applies. See <see cref="LanguageNames"/>.</param> public ExportCodeFixProviderAttribute( string firstLanguage, params string[] additionalLanguages) : base(typeof(CodeFixProvider)) { if (additionalLanguages == null) { throw new ArgumentNullException(nameof(additionalLanguages)); } var languages = new string[additionalLanguages.Length + 1]; languages[0] = firstLanguage ?? throw new ArgumentNullException(nameof(firstLanguage)); for (var index = 0; index < additionalLanguages.Length; index++) { languages[index + 1] = additionalLanguages[index]; } this.Languages = languages; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/VisualBasic/Portable/GenerateType/VisualBasicGenerateTypeService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.AddImport Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor Imports Microsoft.CodeAnalysis.GenerateType Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateType <ExportLanguageService(GetType(IGenerateTypeService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicGenerateTypeService Inherits AbstractGenerateTypeService(Of VisualBasicGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeBlockSyntax, ArgumentSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides ReadOnly Property DefaultFileExtension As String Get Return ".vb" End Get End Property Protected Overrides Function GenerateParameterNames(semanticModel As SemanticModel, arguments As IList(Of ArgumentSyntax), cancellationToken As CancellationToken) As IList(Of ParameterName) Return semanticModel.GenerateParameterNames(arguments, reservedNames:=Nothing, cancellationToken:=cancellationToken) End Function Protected Overrides Function GetLeftSideOfDot(simpleName As SimpleNameSyntax) As ExpressionSyntax Return simpleName.GetLeftSideOfDot() End Function Protected Overrides Function IsArrayElementType(expression As ExpressionSyntax) As Boolean Return expression.IsParentKind(SyntaxKind.ArrayCreationExpression) End Function Protected Overrides Function IsInCatchDeclaration(expression As ExpressionSyntax) As Boolean Return False End Function Protected Overrides Function IsInInterfaceList(expression As ExpressionSyntax) As Boolean If TypeOf expression Is TypeSyntax AndAlso expression.IsParentKind(SyntaxKind.ImplementsStatement) Then Return True End If If TypeOf expression Is TypeSyntax AndAlso expression.IsParentKind(SyntaxKind.TypeConstraint) AndAlso expression.Parent.IsParentKind(SyntaxKind.TypeParameterMultipleConstraintClause) Then ' TODO: Code Coverage Dim typeConstraint = DirectCast(expression.Parent, TypeConstraintSyntax) Dim constraintClause = DirectCast(typeConstraint.Parent, TypeParameterMultipleConstraintClauseSyntax) Dim index = constraintClause.Constraints.IndexOf(typeConstraint) Return index > 0 End If Return False End Function Protected Overrides Function IsInValueTypeConstraintContext(semanticModel As SemanticModel, expression As Microsoft.CodeAnalysis.VisualBasic.Syntax.ExpressionSyntax, cancellationToken As System.Threading.CancellationToken) As Boolean ' TODO(cyrusn) implement this Return False End Function Protected Overrides Function TryGetArgumentList( objectCreationExpression As ObjectCreationExpressionSyntax, ByRef argumentList As IList(Of ArgumentSyntax)) As Boolean If objectCreationExpression IsNot Nothing AndAlso objectCreationExpression.ArgumentList IsNot Nothing Then argumentList = objectCreationExpression.ArgumentList.Arguments.ToList() Return True End If Return False End Function Protected Overrides Function TryGetNameParts(expression As ExpressionSyntax, ByRef nameParts As IList(Of String)) As Boolean Return expression.TryGetNameParts(nameParts) End Function Protected Overrides Function TryInitializeState( document As SemanticDocument, simpleName As SimpleNameSyntax, cancellationToken As CancellationToken, ByRef generateTypeServiceStateOptions As GenerateTypeServiceStateOptions) As Boolean generateTypeServiceStateOptions = New GenerateTypeServiceStateOptions() If simpleName.IsParentKind(SyntaxKind.DictionaryAccessExpression) Then Return False End If Dim nameOrMemberAccessExpression As ExpressionSyntax = Nothing If simpleName.IsRightSideOfDot() Then nameOrMemberAccessExpression = DirectCast(simpleName.Parent, ExpressionSyntax) If Not (TypeOf simpleName.GetLeftSideOfDot() Is NameSyntax) Then Return False End If Else nameOrMemberAccessExpression = simpleName End If generateTypeServiceStateOptions.NameOrMemberAccessExpression = nameOrMemberAccessExpression If TypeOf nameOrMemberAccessExpression.Parent Is BinaryExpressionSyntax Then Return False End If Dim syntaxTree = document.SyntaxTree Dim semanticModel = document.SemanticModel If Not SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression) Then generateTypeServiceStateOptions.IsDelegateAllowed = False Dim position = nameOrMemberAccessExpression.SpanStart Dim isExpressionContext = syntaxTree.IsExpressionContext(position, cancellationToken) Dim isStatementContext = syntaxTree.IsSingleLineStatementContext(position, cancellationToken) Dim isExpressionOrStatementContext = isExpressionContext OrElse isStatementContext If isExpressionOrStatementContext Then If Not simpleName.IsLeftSideOfDot() Then If nameOrMemberAccessExpression Is Nothing OrElse Not nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Return False End If Dim leftSymbol = semanticModel.GetSymbolInfo(DirectCast(nameOrMemberAccessExpression, MemberAccessExpressionSyntax).Expression).Symbol Dim token = simpleName.GetLastToken().GetNextToken() If leftSymbol Is Nothing OrElse Not leftSymbol.IsKind(SymbolKind.Namespace) OrElse Not token.IsKind(SyntaxKind.DotToken) Then Return False Else generateTypeServiceStateOptions.IsMembersWithModule = True generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = True End If End If If Not generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess AndAlso Not SyntaxFacts.IsInNamespaceOrTypeContext(simpleName) Then Dim token = simpleName.GetLastToken().GetNextToken() If token.IsKind(SyntaxKind.DotToken) AndAlso simpleName.Parent Is token.Parent Then generateTypeServiceStateOptions.IsMembersWithModule = True generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = True End If End If End If End If If nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.InvocationExpression) Then Return False End If ' Check if module could be an option Dim nextToken = simpleName.GetLastToken().GetNextToken() If simpleName.IsLeftSideOfDot() OrElse nextToken.IsKind(SyntaxKind.DotToken) Then If simpleName.IsRightSideOfDot() Then Dim parent = TryCast(simpleName.Parent, QualifiedNameSyntax) If parent IsNot Nothing Then Dim leftSymbol = semanticModel.GetSymbolInfo(parent.Left).Symbol If leftSymbol IsNot Nothing And leftSymbol.IsKind(SymbolKind.Namespace) Then generateTypeServiceStateOptions.IsMembersWithModule = True End If End If End If End If If SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression) Then ' In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName If nextToken.IsKind(SyntaxKind.DotToken) Then generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = True generateTypeServiceStateOptions.IsDelegateAllowed = False generateTypeServiceStateOptions.IsMembersWithModule = True End If ' Case : Class Goo(of T as MyType) If nameOrMemberAccessExpression.GetAncestors(Of TypeConstraintSyntax).Any() Then generateTypeServiceStateOptions.IsClassInterfaceTypes = True Return True End If ' Case : Custom Event E As Goo ' Case : Public Event F As Goo If nameOrMemberAccessExpression.GetAncestors(Of EventStatementSyntax)().Any() Then ' Case : Goo ' Only Delegate If simpleName.Parent IsNot Nothing AndAlso TypeOf simpleName.Parent IsNot QualifiedNameSyntax Then generateTypeServiceStateOptions.IsDelegateOnly = True Return True End If ' Case : Something.Goo ... If TypeOf nameOrMemberAccessExpression Is QualifiedNameSyntax Then ' Case : NSOrSomething.GenType.Goo If nextToken.IsKind(SyntaxKind.DotToken) Then If nameOrMemberAccessExpression.Parent IsNot Nothing AndAlso TypeOf nameOrMemberAccessExpression.Parent Is QualifiedNameSyntax Then Return True Else Throw ExceptionUtilities.Unreachable End If Else ' Case : NSOrSomething.GenType generateTypeServiceStateOptions.IsDelegateOnly = True Return True End If End If End If ' Case : Public WithEvents G As Delegate1 Dim fieldDecl = nameOrMemberAccessExpression.GetAncestor(Of FieldDeclarationSyntax)() If fieldDecl IsNot Nothing AndAlso fieldDecl.GetModifiers().Any(Function(n) n.Kind() = SyntaxKind.WithEventsKeyword) Then generateTypeServiceStateOptions.IsClassInterfaceTypes = True Return True End If ' No Enum Type Generation in AddHandler or RemoverHandler Statement If nameOrMemberAccessExpression.GetAncestors(Of AccessorStatementSyntax)().Any() Then If Not nextToken.IsKind(SyntaxKind.DotToken) AndAlso nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleAsClause) AndAlso nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.Parameter) AndAlso nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.ParameterList) AndAlso (nameOrMemberAccessExpression.Parent.Parent.Parent.IsParentKind(SyntaxKind.AddHandlerAccessorStatement) OrElse nameOrMemberAccessExpression.Parent.Parent.Parent.IsParentKind(SyntaxKind.RemoveHandlerAccessorStatement)) Then generateTypeServiceStateOptions.IsDelegateOnly = True Return True End If generateTypeServiceStateOptions.IsEnumNotAllowed = True End If Else ' MemberAccessExpression If nameOrMemberAccessExpression.GetAncestors(Of UnaryExpressionSyntax)().Any(Function(n) n.IsKind(SyntaxKind.AddressOfExpression)) Then generateTypeServiceStateOptions.IsEnumNotAllowed = True End If ' Check to see if the expression is part of Invocation Expression If (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) OrElse (nameOrMemberAccessExpression.Parent IsNot Nothing AndAlso nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))) _ AndAlso nameOrMemberAccessExpression.IsLeftSideOfDot() Then Dim outerMostMemberAccessExpression As ExpressionSyntax = Nothing If nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then outerMostMemberAccessExpression = nameOrMemberAccessExpression Else Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) outerMostMemberAccessExpression = DirectCast(nameOrMemberAccessExpression.Parent, ExpressionSyntax) End If outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis(Of ExpressionSyntax)().SkipWhile(Function(n) n IsNot Nothing AndAlso n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault() If outerMostMemberAccessExpression IsNot Nothing AndAlso TypeOf outerMostMemberAccessExpression Is InvocationExpressionSyntax Then generateTypeServiceStateOptions.IsEnumNotAllowed = True End If End If End If ' New MyDelegate(AddressOf goo) ' New NS.MyDelegate(Function(n) n) If TypeOf nameOrMemberAccessExpression.Parent Is ObjectCreationExpressionSyntax Then Dim objectCreationExpressionOpt = DirectCast(nameOrMemberAccessExpression.Parent, ObjectCreationExpressionSyntax) generateTypeServiceStateOptions.ObjectCreationExpressionOpt = objectCreationExpressionOpt ' Interface and Enum not allowed generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = True If objectCreationExpressionOpt.ArgumentList IsNot Nothing Then If objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing Then Return False End If ' Get the Method Symbol for Delegate to be created ' Currently simple argument is the only argument that can be fed to the Object Creation for Delegate Creation If generateTypeServiceStateOptions.IsDelegateAllowed AndAlso objectCreationExpressionOpt.ArgumentList.Arguments.Count = 1 AndAlso TypeOf objectCreationExpressionOpt.ArgumentList.Arguments(0) Is SimpleArgumentSyntax Then Dim simpleArgumentExpression = DirectCast(objectCreationExpressionOpt.ArgumentList.Arguments(0), SimpleArgumentSyntax).Expression If simpleArgumentExpression.IsKind(SyntaxKind.AddressOfExpression) Then generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMemberGroupIfPresent(semanticModel, DirectCast(simpleArgumentExpression, UnaryExpressionSyntax).Operand, cancellationToken) ElseIf (simpleArgumentExpression.IsKind(SyntaxKind.MultiLineFunctionLambdaExpression) OrElse simpleArgumentExpression.IsKind(SyntaxKind.SingleLineFunctionLambdaExpression) OrElse simpleArgumentExpression.IsKind(SyntaxKind.MultiLineSubLambdaExpression) OrElse simpleArgumentExpression.IsKind(SyntaxKind.SingleLineSubLambdaExpression)) Then generateTypeServiceStateOptions.DelegateCreationMethodSymbol = TryCast(semanticModel.GetSymbolInfo(simpleArgumentExpression, cancellationToken).Symbol, IMethodSymbol) End If ElseIf objectCreationExpressionOpt.ArgumentList.Arguments.Count <> 1 Then generateTypeServiceStateOptions.IsDelegateAllowed = False End If End If Dim initializers = TryCast(objectCreationExpressionOpt.Initializer, ObjectMemberInitializerSyntax) If initializers IsNot Nothing Then For Each initializer In initializers.Initializers.ToList() Dim namedFieldInitializer = TryCast(initializer, NamedFieldInitializerSyntax) If namedFieldInitializer IsNot Nothing Then generateTypeServiceStateOptions.PropertiesToGenerate.Add(namedFieldInitializer.Name) End If Next End If End If Dim variableDeclarator As VariableDeclaratorSyntax = Nothing If generateTypeServiceStateOptions.IsDelegateAllowed Then ' Dim f As MyDel = ... ' Dim f as NS.MyDel = ... If nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleAsClause) AndAlso nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.VariableDeclarator) Then variableDeclarator = DirectCast(nameOrMemberAccessExpression.Parent.Parent, VariableDeclaratorSyntax) If variableDeclarator.Initializer IsNot Nothing AndAlso variableDeclarator.Initializer.Value IsNot Nothing Then Dim expression = variableDeclarator.Initializer.Value If expression.IsKind(SyntaxKind.AddressOfExpression) Then ' ... = AddressOf Goo generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMemberGroupIfPresent(semanticModel, DirectCast(expression, UnaryExpressionSyntax).Operand, cancellationToken) Else If TypeOf expression Is LambdaExpressionSyntax Then '... = Lambda Dim type = semanticModel.GetTypeInfo(expression, cancellationToken).Type If type IsNot Nothing AndAlso type.IsDelegateType() Then generateTypeServiceStateOptions.DelegateCreationMethodSymbol = DirectCast(type, INamedTypeSymbol).DelegateInvokeMethod End If Dim symbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol If symbol IsNot Nothing AndAlso symbol.IsKind(SymbolKind.Method) Then generateTypeServiceStateOptions.DelegateCreationMethodSymbol = DirectCast(symbol, IMethodSymbol) End If End If End If End If ElseIf TypeOf nameOrMemberAccessExpression.Parent Is CastExpressionSyntax Then ' Case: Dim s1 = DirectCast(AddressOf goo, Myy) ' Dim s2 = TryCast(AddressOf goo, Myy) ' Dim s3 = CType(AddressOf goo, Myy) Dim expressionToBeCasted = DirectCast(nameOrMemberAccessExpression.Parent, CastExpressionSyntax).Expression If expressionToBeCasted.IsKind(SyntaxKind.AddressOfExpression) Then ' ... = AddressOf Goo generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMemberGroupIfPresent(semanticModel, DirectCast(expressionToBeCasted, UnaryExpressionSyntax).Operand, cancellationToken) End If End If End If Return True End Function Private Shared Function GetMemberGroupIfPresent(semanticModel As SemanticModel, expression As ExpressionSyntax, cancellationToken As CancellationToken) As IMethodSymbol If expression Is Nothing Then Return Nothing End If Dim memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken) If memberGroup.Length <> 0 Then Return If(memberGroup.ElementAt(0).IsKind(SymbolKind.Method), DirectCast(memberGroup.ElementAt(0), IMethodSymbol), Nothing) End If Return Nothing End Function Public Overrides Function GetRootNamespace(options As CompilationOptions) As String Return DirectCast(options, VisualBasicCompilationOptions).RootNamespace End Function Protected Overloads Overrides Function GetTypeParameters(state As State, semanticModel As SemanticModel, cancellationToken As CancellationToken) As ImmutableArray(Of ITypeParameterSymbol) If TypeOf state.SimpleName Is GenericNameSyntax Then Dim genericName = DirectCast(state.SimpleName, GenericNameSyntax) Dim typeArguments = If(state.SimpleName.Arity = genericName.TypeArgumentList.Arguments.Count, genericName.TypeArgumentList.Arguments.OfType(Of SyntaxNode)().ToList(), Enumerable.Repeat(Of SyntaxNode)(Nothing, state.SimpleName.Arity)) Return GetTypeParameters(state, semanticModel, typeArguments, cancellationToken) End If Return ImmutableArray(Of ITypeParameterSymbol).Empty End Function Protected Overrides Function IsInVariableTypeContext(expression As Microsoft.CodeAnalysis.VisualBasic.Syntax.ExpressionSyntax) As Boolean Return expression.IsParentKind(SyntaxKind.SimpleAsClause) End Function Protected Overrides Function DetermineTypeToGenerateIn(semanticModel As SemanticModel, simpleName As SimpleNameSyntax, cancellationToken As CancellationToken) As INamedTypeSymbol Dim typeBlock = simpleName.GetAncestorsOrThis(Of TypeBlockSyntax). Where(Function(t) t.Members.Count > 0). FirstOrDefault(Function(t) simpleName.SpanStart >= t.Members.First().SpanStart AndAlso simpleName.Span.End <= t.Members.Last().Span.End) Return If(typeBlock Is Nothing, Nothing, TryCast(semanticModel.GetDeclaredSymbol(typeBlock.BlockStatement, cancellationToken), INamedTypeSymbol)) End Function Protected Overrides Function GetAccessibility(state As State, semanticModel As SemanticModel, intoNamespace As Boolean, cancellationToken As CancellationToken) As Accessibility Dim accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken) If Not state.IsTypeGeneratedIntoNamespaceFromMemberAccess Then Dim accessibilityConstraint = semanticModel.DetermineAccessibilityConstraint( TryCast(state.NameOrMemberAccessExpression, TypeSyntax), cancellationToken) If accessibilityConstraint = Accessibility.Public OrElse accessibilityConstraint = Accessibility.Internal Then accessibility = accessibilityConstraint End If End If Return accessibility End Function Protected Overrides Function DetermineArgumentType(semanticModel As SemanticModel, argument As ArgumentSyntax, cancellationToken As CancellationToken) As ITypeSymbol Return argument.DetermineType(semanticModel, cancellationToken) End Function Protected Overrides Function IsConversionImplicit(compilation As Compilation, sourceType As ITypeSymbol, targetType As ITypeSymbol) As Boolean Return compilation.ClassifyConversion(sourceType, targetType).IsWidening End Function Public Overrides Async Function GetOrGenerateEnclosingNamespaceSymbolAsync(namedTypeSymbol As INamedTypeSymbol, containers() As String, selectedDocument As Document, selectedDocumentRoot As SyntaxNode, cancellationToken As CancellationToken) As Task(Of (INamespaceSymbol, INamespaceOrTypeSymbol, Location)) Dim compilationUnit = DirectCast(selectedDocumentRoot, CompilationUnitSyntax) Dim semanticModel = Await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False) If containers.Length <> 0 Then ' Search the NS declaration in the root Dim containerList = New List(Of String)(containers) Dim enclosingNamespace = GetDeclaringNamespace(containerList, 0, compilationUnit) If enclosingNamespace IsNot Nothing Then Dim enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken) If enclosingNamespaceSymbol.Symbol IsNot Nothing Then Return (DirectCast(enclosingNamespaceSymbol.Symbol, INamespaceSymbol), namedTypeSymbol, DirectCast(enclosingNamespace.Parent, NamespaceBlockSyntax).EndNamespaceStatement.GetLocation()) Return Nothing End If End If End If Dim globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken) Dim rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers) Dim lastMember = compilationUnit.Members.LastOrDefault() ' Add at the end Dim afterThisLocation = If(lastMember Is Nothing, semanticModel.SyntaxTree.GetLocation(New TextSpan()), semanticModel.SyntaxTree.GetLocation(New TextSpan(lastMember.Span.End, 0))) Return (globalNamespace, rootNamespaceOrType, afterThisLocation) End Function Private Function GetDeclaringNamespace(containers As List(Of String), indexDone As Integer, compilationUnit As CompilationUnitSyntax) As NamespaceStatementSyntax For Each member In compilationUnit.Members Dim namespaceDeclaration = GetDeclaringNamespace(containers, indexDone, member) If namespaceDeclaration IsNot Nothing Then Return namespaceDeclaration End If Next Return Nothing End Function Private Function GetDeclaringNamespace(containers As List(Of String), indexDone As Integer, localRoot As SyntaxNode) As NamespaceStatementSyntax Dim namespaceBlock = TryCast(localRoot, NamespaceBlockSyntax) If namespaceBlock IsNot Nothing Then Dim matchingNamesCount = MatchingNamesFromNamespaceName(containers, indexDone, namespaceBlock.NamespaceStatement) If matchingNamesCount = -1 Then Return Nothing End If If containers.Count = indexDone + matchingNamesCount Then Return namespaceBlock.NamespaceStatement Else indexDone += matchingNamesCount End If For Each member In namespaceBlock.Members Dim resultantNamespace = GetDeclaringNamespace(containers, indexDone, member) If resultantNamespace IsNot Nothing Then Return resultantNamespace End If Next Return Nothing End If Return Nothing End Function Private Function MatchingNamesFromNamespaceName(containers As List(Of String), indexDone As Integer, namespaceStatementSyntax As NamespaceStatementSyntax) As Integer If namespaceStatementSyntax Is Nothing Then Return -1 End If Dim namespaceContainers = New List(Of String)() GetNamespaceContainers(namespaceStatementSyntax.Name, namespaceContainers) If namespaceContainers.Count + indexDone > containers.Count OrElse Not IdentifierMatches(indexDone, namespaceContainers, containers) Then Return -1 End If Return namespaceContainers.Count End Function Private Shared Function IdentifierMatches(indexDone As Integer, namespaceContainers As List(Of String), containers As List(Of String)) As Boolean For index = 0 To namespaceContainers.Count - 1 If Not namespaceContainers(index).Equals(containers(indexDone + index), StringComparison.OrdinalIgnoreCase) Then Return False End If Next Return True End Function Private Sub GetNamespaceContainers(name As NameSyntax, namespaceContainers As List(Of String)) If TypeOf name Is QualifiedNameSyntax Then GetNamespaceContainers(DirectCast(name, QualifiedNameSyntax).Left, namespaceContainers) namespaceContainers.Add(DirectCast(name, QualifiedNameSyntax).Right.Identifier.ValueText) ElseIf TypeOf name Is SimpleNameSyntax Then namespaceContainers.Add(DirectCast(name, SimpleNameSyntax).Identifier.ValueText) Else Debug.Assert(TypeOf name Is GlobalNameSyntax) namespaceContainers.Add(DirectCast(name, GlobalNameSyntax).GlobalKeyword.ValueText) End If End Sub Friend Overrides Function TryGetBaseList(expression As ExpressionSyntax, ByRef typeKindValue As TypeKindOptions) As Boolean typeKindValue = TypeKindOptions.AllOptions If expression Is Nothing Then Return False End If Dim node As SyntaxNode = expression While node IsNot Nothing If TypeOf node Is InheritsStatementSyntax Then If node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is InterfaceBlockSyntax Then typeKindValue = TypeKindOptions.Interface Return True End If typeKindValue = TypeKindOptions.Class Return True ElseIf TypeOf node Is ImplementsStatementSyntax Then typeKindValue = TypeKindOptions.Interface Return True End If node = node.Parent End While Return False End Function Friend Overrides Function IsPublicOnlyAccessibility(expression As ExpressionSyntax, project As Project) As Boolean If expression Is Nothing Then Return False End If If GeneratedTypesMustBePublic(project) Then Return True End If Dim node As SyntaxNode = expression While node IsNot Nothing ' Types in BaseList, Type Constraint or Member Types cannot be of more restricted accessibility than the declaring type If TypeOf node Is InheritsOrImplementsStatementSyntax AndAlso node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is TypeBlockSyntax Then Return IsAllContainingTypeBlocksPublic(node.Parent) End If If TypeOf node Is TypeParameterListSyntax AndAlso node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is TypeStatementSyntax AndAlso node.Parent.Parent IsNot Nothing AndAlso TypeOf node.Parent.Parent Is TypeBlockSyntax Then Return IsAllContainingTypeBlocksPublic(node.Parent.Parent) End If If TypeOf node Is EventStatementSyntax AndAlso node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is TypeBlockSyntax Then Return IsAllContainingTypeBlocksPublic(node) End If If TypeOf node Is FieldDeclarationSyntax AndAlso node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is TypeBlockSyntax Then Return IsAllContainingTypeBlocksPublic(node) End If node = node.Parent End While Return False End Function Private Shared Function IsAllContainingTypeBlocksPublic(node As SyntaxNode) As Boolean ' Make sure all the Ancestoral Type Blocks are Declared with Public Access Modifiers Dim containingTypeBlocks = node.GetAncestorsOrThis(Of TypeBlockSyntax)() If containingTypeBlocks.Count() = 0 Then Return True Else Return containingTypeBlocks.All(Function(typeBlock) typeBlock.GetModifiers().Any(Function(n) n.Kind() = SyntaxKind.PublicKeyword)) End If End Function Friend Overrides Function IsGenericName(expression As SimpleNameSyntax) As Boolean If expression Is Nothing Then Return False End If Dim node = TryCast(expression, GenericNameSyntax) Return node IsNot Nothing End Function Friend Overrides Function IsSimpleName(expression As ExpressionSyntax) As Boolean Return TypeOf expression Is SimpleNameSyntax End Function Friend Overrides Async Function TryAddUsingsOrImportToDocumentAsync( updatedSolution As Solution, modifiedRoot As SyntaxNode, document As Document, simpleName As SimpleNameSyntax, includeUsingsOrImports As String, fallbackOptions As AddImportPlacementOptionsProvider, cancellationToken As CancellationToken) As Task(Of Solution) ' Nothing to include If String.IsNullOrWhiteSpace(includeUsingsOrImports) Then Return updatedSolution End If Dim root As SyntaxNode = Nothing If modifiedRoot Is Nothing Then root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Else root = modifiedRoot End If If TypeOf root Is CompilationUnitSyntax Then Dim compilationRoot = DirectCast(root, CompilationUnitSyntax) Dim memberImportsClause = SyntaxFactory.SimpleImportsClause( name:=SyntaxFactory.ParseName(includeUsingsOrImports)) Dim lastToken = memberImportsClause.GetLastToken() Dim lastTokenWithEndOfLineTrivia = lastToken.WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed) ' Replace the token the line carriage memberImportsClause = memberImportsClause.ReplaceToken(lastToken, lastTokenWithEndOfLineTrivia) Dim newImport = SyntaxFactory.ImportsStatement( importsClauses:=SyntaxFactory.SingletonSeparatedList(Of ImportsClauseSyntax)(memberImportsClause)) ' Check if the imports is already present Dim importsClauses = compilationRoot.Imports.Select(Function(n) n.ImportsClauses) For Each importClause In importsClauses For Each import In importClause If TypeOf import Is SimpleImportsClauseSyntax Then Dim membersImport = DirectCast(import, SimpleImportsClauseSyntax) If membersImport.Name IsNot Nothing AndAlso membersImport.Name.ToString().Equals(memberImportsClause.Name.ToString()) Then Return updatedSolution End If End If Next Next ' Check if the GFU is triggered from the namespace same as the imports namespace If Await IsWithinTheImportingNamespaceAsync(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken).ConfigureAwait(False) Then Return updatedSolution End If Dim addImportOptions = Await document.GetAddImportPlacementOptionsAsync(fallbackOptions, cancellationToken).ConfigureAwait(False) Dim addedCompilationRoot = compilationRoot.AddImportsStatement(newImport, addImportOptions.PlaceSystemNamespaceFirst, Formatter.Annotation, Simplifier.Annotation) updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity) End If Return updatedSolution End Function Private Shared Function GetPropertyType(propIdentifierName As SimpleNameSyntax, semanticModel As SemanticModel, typeInference As ITypeInferenceService, cancellationToken As CancellationToken) As ITypeSymbol Dim fieldInitializer = TryCast(propIdentifierName.Parent, NamedFieldInitializerSyntax) If fieldInitializer IsNot Nothing Then Return typeInference.InferType(semanticModel, fieldInitializer.Name, True, cancellationToken) End If Return Nothing End Function Private Shared Function GenerateProperty(propertyName As SimpleNameSyntax, typeSymbol As ITypeSymbol) As IPropertySymbol Return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes:=ImmutableArray(Of AttributeData).Empty, accessibility:=Accessibility.Public, modifiers:=New DeclarationModifiers(), explicitInterfaceImplementations:=Nothing, name:=propertyName.ToString, type:=typeSymbol, refKind:=RefKind.None, parameters:=Nothing, getMethod:=Nothing, setMethod:=Nothing, isIndexer:=False) End Function Friend Overrides Function TryGenerateProperty(propertyName As SimpleNameSyntax, semanticModel As SemanticModel, typeInferenceService As ITypeInferenceService, cancellationToken As CancellationToken, ByRef propertySymbol As IPropertySymbol) As Boolean Dim typeSymbol = GetPropertyType(propertyName, semanticModel, typeInferenceService, cancellationToken) If typeSymbol Is Nothing OrElse TypeOf typeSymbol Is IErrorTypeSymbol Then propertySymbol = GenerateProperty(propertyName, semanticModel.Compilation.ObjectType) Return propertySymbol IsNot Nothing End If propertySymbol = GenerateProperty(propertyName, typeSymbol) Return propertySymbol 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.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.AddImport Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor Imports Microsoft.CodeAnalysis.GenerateType Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateType <ExportLanguageService(GetType(IGenerateTypeService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicGenerateTypeService Inherits AbstractGenerateTypeService(Of VisualBasicGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeBlockSyntax, ArgumentSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides ReadOnly Property DefaultFileExtension As String Get Return ".vb" End Get End Property Protected Overrides Function GenerateParameterNames(semanticModel As SemanticModel, arguments As IList(Of ArgumentSyntax), cancellationToken As CancellationToken) As IList(Of ParameterName) Return semanticModel.GenerateParameterNames(arguments, reservedNames:=Nothing, cancellationToken:=cancellationToken) End Function Protected Overrides Function GetLeftSideOfDot(simpleName As SimpleNameSyntax) As ExpressionSyntax Return simpleName.GetLeftSideOfDot() End Function Protected Overrides Function IsArrayElementType(expression As ExpressionSyntax) As Boolean Return expression.IsParentKind(SyntaxKind.ArrayCreationExpression) End Function Protected Overrides Function IsInCatchDeclaration(expression As ExpressionSyntax) As Boolean Return False End Function Protected Overrides Function IsInInterfaceList(expression As ExpressionSyntax) As Boolean If TypeOf expression Is TypeSyntax AndAlso expression.IsParentKind(SyntaxKind.ImplementsStatement) Then Return True End If If TypeOf expression Is TypeSyntax AndAlso expression.IsParentKind(SyntaxKind.TypeConstraint) AndAlso expression.Parent.IsParentKind(SyntaxKind.TypeParameterMultipleConstraintClause) Then ' TODO: Code Coverage Dim typeConstraint = DirectCast(expression.Parent, TypeConstraintSyntax) Dim constraintClause = DirectCast(typeConstraint.Parent, TypeParameterMultipleConstraintClauseSyntax) Dim index = constraintClause.Constraints.IndexOf(typeConstraint) Return index > 0 End If Return False End Function Protected Overrides Function IsInValueTypeConstraintContext(semanticModel As SemanticModel, expression As Microsoft.CodeAnalysis.VisualBasic.Syntax.ExpressionSyntax, cancellationToken As System.Threading.CancellationToken) As Boolean ' TODO(cyrusn) implement this Return False End Function Protected Overrides Function TryGetArgumentList( objectCreationExpression As ObjectCreationExpressionSyntax, ByRef argumentList As IList(Of ArgumentSyntax)) As Boolean If objectCreationExpression IsNot Nothing AndAlso objectCreationExpression.ArgumentList IsNot Nothing Then argumentList = objectCreationExpression.ArgumentList.Arguments.ToList() Return True End If Return False End Function Protected Overrides Function TryGetNameParts(expression As ExpressionSyntax, ByRef nameParts As IList(Of String)) As Boolean Return expression.TryGetNameParts(nameParts) End Function Protected Overrides Function TryInitializeState( document As SemanticDocument, simpleName As SimpleNameSyntax, cancellationToken As CancellationToken, ByRef generateTypeServiceStateOptions As GenerateTypeServiceStateOptions) As Boolean generateTypeServiceStateOptions = New GenerateTypeServiceStateOptions() If simpleName.IsParentKind(SyntaxKind.DictionaryAccessExpression) Then Return False End If Dim nameOrMemberAccessExpression As ExpressionSyntax = Nothing If simpleName.IsRightSideOfDot() Then nameOrMemberAccessExpression = DirectCast(simpleName.Parent, ExpressionSyntax) If Not (TypeOf simpleName.GetLeftSideOfDot() Is NameSyntax) Then Return False End If Else nameOrMemberAccessExpression = simpleName End If generateTypeServiceStateOptions.NameOrMemberAccessExpression = nameOrMemberAccessExpression If TypeOf nameOrMemberAccessExpression.Parent Is BinaryExpressionSyntax Then Return False End If Dim syntaxTree = document.SyntaxTree Dim semanticModel = document.SemanticModel If Not SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression) Then generateTypeServiceStateOptions.IsDelegateAllowed = False Dim position = nameOrMemberAccessExpression.SpanStart Dim isExpressionContext = syntaxTree.IsExpressionContext(position, cancellationToken) Dim isStatementContext = syntaxTree.IsSingleLineStatementContext(position, cancellationToken) Dim isExpressionOrStatementContext = isExpressionContext OrElse isStatementContext If isExpressionOrStatementContext Then If Not simpleName.IsLeftSideOfDot() Then If nameOrMemberAccessExpression Is Nothing OrElse Not nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Return False End If Dim leftSymbol = semanticModel.GetSymbolInfo(DirectCast(nameOrMemberAccessExpression, MemberAccessExpressionSyntax).Expression).Symbol Dim token = simpleName.GetLastToken().GetNextToken() If leftSymbol Is Nothing OrElse Not leftSymbol.IsKind(SymbolKind.Namespace) OrElse Not token.IsKind(SyntaxKind.DotToken) Then Return False Else generateTypeServiceStateOptions.IsMembersWithModule = True generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = True End If End If If Not generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess AndAlso Not SyntaxFacts.IsInNamespaceOrTypeContext(simpleName) Then Dim token = simpleName.GetLastToken().GetNextToken() If token.IsKind(SyntaxKind.DotToken) AndAlso simpleName.Parent Is token.Parent Then generateTypeServiceStateOptions.IsMembersWithModule = True generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = True End If End If End If End If If nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.InvocationExpression) Then Return False End If ' Check if module could be an option Dim nextToken = simpleName.GetLastToken().GetNextToken() If simpleName.IsLeftSideOfDot() OrElse nextToken.IsKind(SyntaxKind.DotToken) Then If simpleName.IsRightSideOfDot() Then Dim parent = TryCast(simpleName.Parent, QualifiedNameSyntax) If parent IsNot Nothing Then Dim leftSymbol = semanticModel.GetSymbolInfo(parent.Left).Symbol If leftSymbol IsNot Nothing And leftSymbol.IsKind(SymbolKind.Namespace) Then generateTypeServiceStateOptions.IsMembersWithModule = True End If End If End If End If If SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression) Then ' In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName If nextToken.IsKind(SyntaxKind.DotToken) Then generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = True generateTypeServiceStateOptions.IsDelegateAllowed = False generateTypeServiceStateOptions.IsMembersWithModule = True End If ' Case : Class Goo(of T as MyType) If nameOrMemberAccessExpression.GetAncestors(Of TypeConstraintSyntax).Any() Then generateTypeServiceStateOptions.IsClassInterfaceTypes = True Return True End If ' Case : Custom Event E As Goo ' Case : Public Event F As Goo If nameOrMemberAccessExpression.GetAncestors(Of EventStatementSyntax)().Any() Then ' Case : Goo ' Only Delegate If simpleName.Parent IsNot Nothing AndAlso TypeOf simpleName.Parent IsNot QualifiedNameSyntax Then generateTypeServiceStateOptions.IsDelegateOnly = True Return True End If ' Case : Something.Goo ... If TypeOf nameOrMemberAccessExpression Is QualifiedNameSyntax Then ' Case : NSOrSomething.GenType.Goo If nextToken.IsKind(SyntaxKind.DotToken) Then If nameOrMemberAccessExpression.Parent IsNot Nothing AndAlso TypeOf nameOrMemberAccessExpression.Parent Is QualifiedNameSyntax Then Return True Else Throw ExceptionUtilities.Unreachable End If Else ' Case : NSOrSomething.GenType generateTypeServiceStateOptions.IsDelegateOnly = True Return True End If End If End If ' Case : Public WithEvents G As Delegate1 Dim fieldDecl = nameOrMemberAccessExpression.GetAncestor(Of FieldDeclarationSyntax)() If fieldDecl IsNot Nothing AndAlso fieldDecl.GetModifiers().Any(Function(n) n.Kind() = SyntaxKind.WithEventsKeyword) Then generateTypeServiceStateOptions.IsClassInterfaceTypes = True Return True End If ' No Enum Type Generation in AddHandler or RemoverHandler Statement If nameOrMemberAccessExpression.GetAncestors(Of AccessorStatementSyntax)().Any() Then If Not nextToken.IsKind(SyntaxKind.DotToken) AndAlso nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleAsClause) AndAlso nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.Parameter) AndAlso nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.ParameterList) AndAlso (nameOrMemberAccessExpression.Parent.Parent.Parent.IsParentKind(SyntaxKind.AddHandlerAccessorStatement) OrElse nameOrMemberAccessExpression.Parent.Parent.Parent.IsParentKind(SyntaxKind.RemoveHandlerAccessorStatement)) Then generateTypeServiceStateOptions.IsDelegateOnly = True Return True End If generateTypeServiceStateOptions.IsEnumNotAllowed = True End If Else ' MemberAccessExpression If nameOrMemberAccessExpression.GetAncestors(Of UnaryExpressionSyntax)().Any(Function(n) n.IsKind(SyntaxKind.AddressOfExpression)) Then generateTypeServiceStateOptions.IsEnumNotAllowed = True End If ' Check to see if the expression is part of Invocation Expression If (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) OrElse (nameOrMemberAccessExpression.Parent IsNot Nothing AndAlso nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))) _ AndAlso nameOrMemberAccessExpression.IsLeftSideOfDot() Then Dim outerMostMemberAccessExpression As ExpressionSyntax = Nothing If nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then outerMostMemberAccessExpression = nameOrMemberAccessExpression Else Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) outerMostMemberAccessExpression = DirectCast(nameOrMemberAccessExpression.Parent, ExpressionSyntax) End If outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis(Of ExpressionSyntax)().SkipWhile(Function(n) n IsNot Nothing AndAlso n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault() If outerMostMemberAccessExpression IsNot Nothing AndAlso TypeOf outerMostMemberAccessExpression Is InvocationExpressionSyntax Then generateTypeServiceStateOptions.IsEnumNotAllowed = True End If End If End If ' New MyDelegate(AddressOf goo) ' New NS.MyDelegate(Function(n) n) If TypeOf nameOrMemberAccessExpression.Parent Is ObjectCreationExpressionSyntax Then Dim objectCreationExpressionOpt = DirectCast(nameOrMemberAccessExpression.Parent, ObjectCreationExpressionSyntax) generateTypeServiceStateOptions.ObjectCreationExpressionOpt = objectCreationExpressionOpt ' Interface and Enum not allowed generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = True If objectCreationExpressionOpt.ArgumentList IsNot Nothing Then If objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing Then Return False End If ' Get the Method Symbol for Delegate to be created ' Currently simple argument is the only argument that can be fed to the Object Creation for Delegate Creation If generateTypeServiceStateOptions.IsDelegateAllowed AndAlso objectCreationExpressionOpt.ArgumentList.Arguments.Count = 1 AndAlso TypeOf objectCreationExpressionOpt.ArgumentList.Arguments(0) Is SimpleArgumentSyntax Then Dim simpleArgumentExpression = DirectCast(objectCreationExpressionOpt.ArgumentList.Arguments(0), SimpleArgumentSyntax).Expression If simpleArgumentExpression.IsKind(SyntaxKind.AddressOfExpression) Then generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMemberGroupIfPresent(semanticModel, DirectCast(simpleArgumentExpression, UnaryExpressionSyntax).Operand, cancellationToken) ElseIf (simpleArgumentExpression.IsKind(SyntaxKind.MultiLineFunctionLambdaExpression) OrElse simpleArgumentExpression.IsKind(SyntaxKind.SingleLineFunctionLambdaExpression) OrElse simpleArgumentExpression.IsKind(SyntaxKind.MultiLineSubLambdaExpression) OrElse simpleArgumentExpression.IsKind(SyntaxKind.SingleLineSubLambdaExpression)) Then generateTypeServiceStateOptions.DelegateCreationMethodSymbol = TryCast(semanticModel.GetSymbolInfo(simpleArgumentExpression, cancellationToken).Symbol, IMethodSymbol) End If ElseIf objectCreationExpressionOpt.ArgumentList.Arguments.Count <> 1 Then generateTypeServiceStateOptions.IsDelegateAllowed = False End If End If Dim initializers = TryCast(objectCreationExpressionOpt.Initializer, ObjectMemberInitializerSyntax) If initializers IsNot Nothing Then For Each initializer In initializers.Initializers.ToList() Dim namedFieldInitializer = TryCast(initializer, NamedFieldInitializerSyntax) If namedFieldInitializer IsNot Nothing Then generateTypeServiceStateOptions.PropertiesToGenerate.Add(namedFieldInitializer.Name) End If Next End If End If Dim variableDeclarator As VariableDeclaratorSyntax = Nothing If generateTypeServiceStateOptions.IsDelegateAllowed Then ' Dim f As MyDel = ... ' Dim f as NS.MyDel = ... If nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleAsClause) AndAlso nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.VariableDeclarator) Then variableDeclarator = DirectCast(nameOrMemberAccessExpression.Parent.Parent, VariableDeclaratorSyntax) If variableDeclarator.Initializer IsNot Nothing AndAlso variableDeclarator.Initializer.Value IsNot Nothing Then Dim expression = variableDeclarator.Initializer.Value If expression.IsKind(SyntaxKind.AddressOfExpression) Then ' ... = AddressOf Goo generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMemberGroupIfPresent(semanticModel, DirectCast(expression, UnaryExpressionSyntax).Operand, cancellationToken) Else If TypeOf expression Is LambdaExpressionSyntax Then '... = Lambda Dim type = semanticModel.GetTypeInfo(expression, cancellationToken).Type If type IsNot Nothing AndAlso type.IsDelegateType() Then generateTypeServiceStateOptions.DelegateCreationMethodSymbol = DirectCast(type, INamedTypeSymbol).DelegateInvokeMethod End If Dim symbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol If symbol IsNot Nothing AndAlso symbol.IsKind(SymbolKind.Method) Then generateTypeServiceStateOptions.DelegateCreationMethodSymbol = DirectCast(symbol, IMethodSymbol) End If End If End If End If ElseIf TypeOf nameOrMemberAccessExpression.Parent Is CastExpressionSyntax Then ' Case: Dim s1 = DirectCast(AddressOf goo, Myy) ' Dim s2 = TryCast(AddressOf goo, Myy) ' Dim s3 = CType(AddressOf goo, Myy) Dim expressionToBeCasted = DirectCast(nameOrMemberAccessExpression.Parent, CastExpressionSyntax).Expression If expressionToBeCasted.IsKind(SyntaxKind.AddressOfExpression) Then ' ... = AddressOf Goo generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMemberGroupIfPresent(semanticModel, DirectCast(expressionToBeCasted, UnaryExpressionSyntax).Operand, cancellationToken) End If End If End If Return True End Function Private Shared Function GetMemberGroupIfPresent(semanticModel As SemanticModel, expression As ExpressionSyntax, cancellationToken As CancellationToken) As IMethodSymbol If expression Is Nothing Then Return Nothing End If Dim memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken) If memberGroup.Length <> 0 Then Return If(memberGroup.ElementAt(0).IsKind(SymbolKind.Method), DirectCast(memberGroup.ElementAt(0), IMethodSymbol), Nothing) End If Return Nothing End Function Public Overrides Function GetRootNamespace(options As CompilationOptions) As String Return DirectCast(options, VisualBasicCompilationOptions).RootNamespace End Function Protected Overloads Overrides Function GetTypeParameters(state As State, semanticModel As SemanticModel, cancellationToken As CancellationToken) As ImmutableArray(Of ITypeParameterSymbol) If TypeOf state.SimpleName Is GenericNameSyntax Then Dim genericName = DirectCast(state.SimpleName, GenericNameSyntax) Dim typeArguments = If(state.SimpleName.Arity = genericName.TypeArgumentList.Arguments.Count, genericName.TypeArgumentList.Arguments.OfType(Of SyntaxNode)().ToList(), Enumerable.Repeat(Of SyntaxNode)(Nothing, state.SimpleName.Arity)) Return GetTypeParameters(state, semanticModel, typeArguments, cancellationToken) End If Return ImmutableArray(Of ITypeParameterSymbol).Empty End Function Protected Overrides Function IsInVariableTypeContext(expression As Microsoft.CodeAnalysis.VisualBasic.Syntax.ExpressionSyntax) As Boolean Return expression.IsParentKind(SyntaxKind.SimpleAsClause) End Function Protected Overrides Function DetermineTypeToGenerateIn(semanticModel As SemanticModel, simpleName As SimpleNameSyntax, cancellationToken As CancellationToken) As INamedTypeSymbol Dim typeBlock = simpleName.GetAncestorsOrThis(Of TypeBlockSyntax). Where(Function(t) t.Members.Count > 0). FirstOrDefault(Function(t) simpleName.SpanStart >= t.Members.First().SpanStart AndAlso simpleName.Span.End <= t.Members.Last().Span.End) Return If(typeBlock Is Nothing, Nothing, TryCast(semanticModel.GetDeclaredSymbol(typeBlock.BlockStatement, cancellationToken), INamedTypeSymbol)) End Function Protected Overrides Function GetAccessibility(state As State, semanticModel As SemanticModel, intoNamespace As Boolean, cancellationToken As CancellationToken) As Accessibility Dim accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken) If Not state.IsTypeGeneratedIntoNamespaceFromMemberAccess Then Dim accessibilityConstraint = semanticModel.DetermineAccessibilityConstraint( TryCast(state.NameOrMemberAccessExpression, TypeSyntax), cancellationToken) If accessibilityConstraint = Accessibility.Public OrElse accessibilityConstraint = Accessibility.Internal Then accessibility = accessibilityConstraint End If End If Return accessibility End Function Protected Overrides Function DetermineArgumentType(semanticModel As SemanticModel, argument As ArgumentSyntax, cancellationToken As CancellationToken) As ITypeSymbol Return argument.DetermineType(semanticModel, cancellationToken) End Function Protected Overrides Function IsConversionImplicit(compilation As Compilation, sourceType As ITypeSymbol, targetType As ITypeSymbol) As Boolean Return compilation.ClassifyConversion(sourceType, targetType).IsWidening End Function Public Overrides Async Function GetOrGenerateEnclosingNamespaceSymbolAsync(namedTypeSymbol As INamedTypeSymbol, containers() As String, selectedDocument As Document, selectedDocumentRoot As SyntaxNode, cancellationToken As CancellationToken) As Task(Of (INamespaceSymbol, INamespaceOrTypeSymbol, Location)) Dim compilationUnit = DirectCast(selectedDocumentRoot, CompilationUnitSyntax) Dim semanticModel = Await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False) If containers.Length <> 0 Then ' Search the NS declaration in the root Dim containerList = New List(Of String)(containers) Dim enclosingNamespace = GetDeclaringNamespace(containerList, 0, compilationUnit) If enclosingNamespace IsNot Nothing Then Dim enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken) If enclosingNamespaceSymbol.Symbol IsNot Nothing Then Return (DirectCast(enclosingNamespaceSymbol.Symbol, INamespaceSymbol), namedTypeSymbol, DirectCast(enclosingNamespace.Parent, NamespaceBlockSyntax).EndNamespaceStatement.GetLocation()) Return Nothing End If End If End If Dim globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken) Dim rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers) Dim lastMember = compilationUnit.Members.LastOrDefault() ' Add at the end Dim afterThisLocation = If(lastMember Is Nothing, semanticModel.SyntaxTree.GetLocation(New TextSpan()), semanticModel.SyntaxTree.GetLocation(New TextSpan(lastMember.Span.End, 0))) Return (globalNamespace, rootNamespaceOrType, afterThisLocation) End Function Private Function GetDeclaringNamespace(containers As List(Of String), indexDone As Integer, compilationUnit As CompilationUnitSyntax) As NamespaceStatementSyntax For Each member In compilationUnit.Members Dim namespaceDeclaration = GetDeclaringNamespace(containers, indexDone, member) If namespaceDeclaration IsNot Nothing Then Return namespaceDeclaration End If Next Return Nothing End Function Private Function GetDeclaringNamespace(containers As List(Of String), indexDone As Integer, localRoot As SyntaxNode) As NamespaceStatementSyntax Dim namespaceBlock = TryCast(localRoot, NamespaceBlockSyntax) If namespaceBlock IsNot Nothing Then Dim matchingNamesCount = MatchingNamesFromNamespaceName(containers, indexDone, namespaceBlock.NamespaceStatement) If matchingNamesCount = -1 Then Return Nothing End If If containers.Count = indexDone + matchingNamesCount Then Return namespaceBlock.NamespaceStatement Else indexDone += matchingNamesCount End If For Each member In namespaceBlock.Members Dim resultantNamespace = GetDeclaringNamespace(containers, indexDone, member) If resultantNamespace IsNot Nothing Then Return resultantNamespace End If Next Return Nothing End If Return Nothing End Function Private Function MatchingNamesFromNamespaceName(containers As List(Of String), indexDone As Integer, namespaceStatementSyntax As NamespaceStatementSyntax) As Integer If namespaceStatementSyntax Is Nothing Then Return -1 End If Dim namespaceContainers = New List(Of String)() GetNamespaceContainers(namespaceStatementSyntax.Name, namespaceContainers) If namespaceContainers.Count + indexDone > containers.Count OrElse Not IdentifierMatches(indexDone, namespaceContainers, containers) Then Return -1 End If Return namespaceContainers.Count End Function Private Shared Function IdentifierMatches(indexDone As Integer, namespaceContainers As List(Of String), containers As List(Of String)) As Boolean For index = 0 To namespaceContainers.Count - 1 If Not namespaceContainers(index).Equals(containers(indexDone + index), StringComparison.OrdinalIgnoreCase) Then Return False End If Next Return True End Function Private Sub GetNamespaceContainers(name As NameSyntax, namespaceContainers As List(Of String)) If TypeOf name Is QualifiedNameSyntax Then GetNamespaceContainers(DirectCast(name, QualifiedNameSyntax).Left, namespaceContainers) namespaceContainers.Add(DirectCast(name, QualifiedNameSyntax).Right.Identifier.ValueText) ElseIf TypeOf name Is SimpleNameSyntax Then namespaceContainers.Add(DirectCast(name, SimpleNameSyntax).Identifier.ValueText) Else Debug.Assert(TypeOf name Is GlobalNameSyntax) namespaceContainers.Add(DirectCast(name, GlobalNameSyntax).GlobalKeyword.ValueText) End If End Sub Friend Overrides Function TryGetBaseList(expression As ExpressionSyntax, ByRef typeKindValue As TypeKindOptions) As Boolean typeKindValue = TypeKindOptions.AllOptions If expression Is Nothing Then Return False End If Dim node As SyntaxNode = expression While node IsNot Nothing If TypeOf node Is InheritsStatementSyntax Then If node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is InterfaceBlockSyntax Then typeKindValue = TypeKindOptions.Interface Return True End If typeKindValue = TypeKindOptions.Class Return True ElseIf TypeOf node Is ImplementsStatementSyntax Then typeKindValue = TypeKindOptions.Interface Return True End If node = node.Parent End While Return False End Function Friend Overrides Function IsPublicOnlyAccessibility(expression As ExpressionSyntax, project As Project) As Boolean If expression Is Nothing Then Return False End If If GeneratedTypesMustBePublic(project) Then Return True End If Dim node As SyntaxNode = expression While node IsNot Nothing ' Types in BaseList, Type Constraint or Member Types cannot be of more restricted accessibility than the declaring type If TypeOf node Is InheritsOrImplementsStatementSyntax AndAlso node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is TypeBlockSyntax Then Return IsAllContainingTypeBlocksPublic(node.Parent) End If If TypeOf node Is TypeParameterListSyntax AndAlso node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is TypeStatementSyntax AndAlso node.Parent.Parent IsNot Nothing AndAlso TypeOf node.Parent.Parent Is TypeBlockSyntax Then Return IsAllContainingTypeBlocksPublic(node.Parent.Parent) End If If TypeOf node Is EventStatementSyntax AndAlso node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is TypeBlockSyntax Then Return IsAllContainingTypeBlocksPublic(node) End If If TypeOf node Is FieldDeclarationSyntax AndAlso node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is TypeBlockSyntax Then Return IsAllContainingTypeBlocksPublic(node) End If node = node.Parent End While Return False End Function Private Shared Function IsAllContainingTypeBlocksPublic(node As SyntaxNode) As Boolean ' Make sure all the Ancestoral Type Blocks are Declared with Public Access Modifiers Dim containingTypeBlocks = node.GetAncestorsOrThis(Of TypeBlockSyntax)() If containingTypeBlocks.Count() = 0 Then Return True Else Return containingTypeBlocks.All(Function(typeBlock) typeBlock.GetModifiers().Any(Function(n) n.Kind() = SyntaxKind.PublicKeyword)) End If End Function Friend Overrides Function IsGenericName(expression As SimpleNameSyntax) As Boolean If expression Is Nothing Then Return False End If Dim node = TryCast(expression, GenericNameSyntax) Return node IsNot Nothing End Function Friend Overrides Function IsSimpleName(expression As ExpressionSyntax) As Boolean Return TypeOf expression Is SimpleNameSyntax End Function Friend Overrides Async Function TryAddUsingsOrImportToDocumentAsync( updatedSolution As Solution, modifiedRoot As SyntaxNode, document As Document, simpleName As SimpleNameSyntax, includeUsingsOrImports As String, fallbackOptions As AddImportPlacementOptionsProvider, cancellationToken As CancellationToken) As Task(Of Solution) ' Nothing to include If String.IsNullOrWhiteSpace(includeUsingsOrImports) Then Return updatedSolution End If Dim root As SyntaxNode = Nothing If modifiedRoot Is Nothing Then root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Else root = modifiedRoot End If If TypeOf root Is CompilationUnitSyntax Then Dim compilationRoot = DirectCast(root, CompilationUnitSyntax) Dim memberImportsClause = SyntaxFactory.SimpleImportsClause( name:=SyntaxFactory.ParseName(includeUsingsOrImports)) Dim lastToken = memberImportsClause.GetLastToken() Dim lastTokenWithEndOfLineTrivia = lastToken.WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed) ' Replace the token the line carriage memberImportsClause = memberImportsClause.ReplaceToken(lastToken, lastTokenWithEndOfLineTrivia) Dim newImport = SyntaxFactory.ImportsStatement( importsClauses:=SyntaxFactory.SingletonSeparatedList(Of ImportsClauseSyntax)(memberImportsClause)) ' Check if the imports is already present Dim importsClauses = compilationRoot.Imports.Select(Function(n) n.ImportsClauses) For Each importClause In importsClauses For Each import In importClause If TypeOf import Is SimpleImportsClauseSyntax Then Dim membersImport = DirectCast(import, SimpleImportsClauseSyntax) If membersImport.Name IsNot Nothing AndAlso membersImport.Name.ToString().Equals(memberImportsClause.Name.ToString()) Then Return updatedSolution End If End If Next Next ' Check if the GFU is triggered from the namespace same as the imports namespace If Await IsWithinTheImportingNamespaceAsync(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken).ConfigureAwait(False) Then Return updatedSolution End If Dim addImportOptions = Await document.GetAddImportPlacementOptionsAsync(fallbackOptions, cancellationToken).ConfigureAwait(False) Dim addedCompilationRoot = compilationRoot.AddImportsStatement(newImport, addImportOptions.PlaceSystemNamespaceFirst, Formatter.Annotation, Simplifier.Annotation) updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity) End If Return updatedSolution End Function Private Shared Function GetPropertyType(propIdentifierName As SimpleNameSyntax, semanticModel As SemanticModel, typeInference As ITypeInferenceService, cancellationToken As CancellationToken) As ITypeSymbol Dim fieldInitializer = TryCast(propIdentifierName.Parent, NamedFieldInitializerSyntax) If fieldInitializer IsNot Nothing Then Return typeInference.InferType(semanticModel, fieldInitializer.Name, True, cancellationToken) End If Return Nothing End Function Private Shared Function GenerateProperty(propertyName As SimpleNameSyntax, typeSymbol As ITypeSymbol) As IPropertySymbol Return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes:=ImmutableArray(Of AttributeData).Empty, accessibility:=Accessibility.Public, modifiers:=New DeclarationModifiers(), explicitInterfaceImplementations:=Nothing, name:=propertyName.ToString, type:=typeSymbol, refKind:=RefKind.None, parameters:=Nothing, getMethod:=Nothing, setMethod:=Nothing, isIndexer:=False) End Function Friend Overrides Function TryGenerateProperty(propertyName As SimpleNameSyntax, semanticModel As SemanticModel, typeInferenceService As ITypeInferenceService, cancellationToken As CancellationToken, ByRef propertySymbol As IPropertySymbol) As Boolean Dim typeSymbol = GetPropertyType(propertyName, semanticModel, typeInferenceService, cancellationToken) If typeSymbol Is Nothing OrElse TypeOf typeSymbol Is IErrorTypeSymbol Then propertySymbol = GenerateProperty(propertyName, semanticModel.Compilation.ObjectType) Return propertySymbol IsNot Nothing End If propertySymbol = GenerateProperty(propertyName, typeSymbol) Return propertySymbol IsNot Nothing End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Formatter = Microsoft.CodeAnalysis.Formatting.FormatterHelper; using FormattingProvider = Microsoft.CodeAnalysis.Formatting.ISyntaxFormatting; namespace Microsoft.CodeAnalysis { internal static class FormattingCodeFixHelper { internal static async Task<SyntaxTree> FixOneAsync(SyntaxTree syntaxTree, FormattingProvider formattingProvider, SyntaxFormattingOptions options, Diagnostic diagnostic, CancellationToken cancellationToken) { // The span to format is the full line(s) containing the diagnostic var text = await syntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); var diagnosticSpan = diagnostic.Location.SourceSpan; var diagnosticLinePositionSpan = text.Lines.GetLinePositionSpan(diagnosticSpan); var spanToFormat = TextSpan.FromBounds( text.Lines[diagnosticLinePositionSpan.Start.Line].Start, text.Lines[diagnosticLinePositionSpan.End.Line].End); var root = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var formattedRoot = Formatter.Format(root, spanToFormat, formattingProvider, options, cancellationToken); return syntaxTree.WithRootAndOptions(formattedRoot, syntaxTree.Options); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Formatter = Microsoft.CodeAnalysis.Formatting.FormatterHelper; using FormattingProvider = Microsoft.CodeAnalysis.Formatting.ISyntaxFormatting; namespace Microsoft.CodeAnalysis { internal static class FormattingCodeFixHelper { internal static async Task<SyntaxTree> FixOneAsync(SyntaxTree syntaxTree, FormattingProvider formattingProvider, SyntaxFormattingOptions options, Diagnostic diagnostic, CancellationToken cancellationToken) { // The span to format is the full line(s) containing the diagnostic var text = await syntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); var diagnosticSpan = diagnostic.Location.SourceSpan; var diagnosticLinePositionSpan = text.Lines.GetLinePositionSpan(diagnosticSpan); var spanToFormat = TextSpan.FromBounds( text.Lines[diagnosticLinePositionSpan.Start.Line].Start, text.Lines[diagnosticLinePositionSpan.End.Line].End); var root = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var formattedRoot = Formatter.Format(root, spanToFormat, formattingProvider, options, cancellationToken); return syntaxTree.WithRootAndOptions(formattedRoot, syntaxTree.Options); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/Core/Portable/EmbeddedLanguages/Json/LanguageServices/JsonEmbeddedLanguage.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Completion.Providers; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.EmbeddedLanguages; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.Json.LanguageServices { internal class JsonEmbeddedLanguage : IEmbeddedLanguage { // No completion for embedded json currently. public EmbeddedLanguageCompletionProvider? CompletionProvider => 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 Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.EmbeddedLanguages; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.Json.LanguageServices { internal class JsonEmbeddedLanguage : IEmbeddedLanguage { // No completion for embedded json currently. public EmbeddedLanguageCompletionProvider? CompletionProvider => null; } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/CSharp/Test/Interactive/TestInteractiveEvaluator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Interactive; using Microsoft.VisualStudio.InteractiveWindow; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive { internal sealed class TestInteractiveEvaluator : IInteractiveEvaluator, IResettableInteractiveEvaluator { internal event EventHandler<string> OnExecute; public IInteractiveWindow CurrentWindow { get; set; } public InteractiveEvaluatorResetOptions ResetOptions { get; set; } public void Dispose() { } public Task<ExecutionResult> InitializeAsync() => Task.FromResult(ExecutionResult.Success); public Task<ExecutionResult> ResetAsync(bool initialize = true) => Task.FromResult(ExecutionResult.Success); public bool CanExecuteCode(string text) => true; public Task<ExecutionResult> ExecuteCodeAsync(string text) { OnExecute?.Invoke(this, text); return Task.FromResult(ExecutionResult.Success); } public string FormatClipboard() => null; public void AbortExecution() { } public string GetConfiguration() => "config"; public string GetPrompt() => "> "; public Task SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string workingDirectory) => Task.CompletedTask; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Interactive; using Microsoft.VisualStudio.InteractiveWindow; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive { internal sealed class TestInteractiveEvaluator : IInteractiveEvaluator, IResettableInteractiveEvaluator { internal event EventHandler<string> OnExecute; public IInteractiveWindow CurrentWindow { get; set; } public InteractiveEvaluatorResetOptions ResetOptions { get; set; } public void Dispose() { } public Task<ExecutionResult> InitializeAsync() => Task.FromResult(ExecutionResult.Success); public Task<ExecutionResult> ResetAsync(bool initialize = true) => Task.FromResult(ExecutionResult.Success); public bool CanExecuteCode(string text) => true; public Task<ExecutionResult> ExecuteCodeAsync(string text) { OnExecute?.Invoke(this, text); return Task.FromResult(ExecutionResult.Success); } public string FormatClipboard() => null; public void AbortExecution() { } public string GetConfiguration() => "config"; public string GetPrompt() => "> "; public Task SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string workingDirectory) => Task.CompletedTask; } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/Symbols/TypeSymbolExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static partial class TypeSymbolExtensions { public static bool ImplementsInterface(this TypeSymbol subType, TypeSymbol superInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { foreach (NamedTypeSymbol @interface in subType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (@interface.IsInterface && TypeSymbol.Equals(@interface, superInterface, TypeCompareKind.ConsiderEverything2)) { return true; } } return false; } public static bool CanBeAssignedNull(this TypeSymbol type) { return type.IsReferenceType || type.IsPointerOrFunctionPointer() || type.IsNullableType(); } public static bool CanContainNull(this TypeSymbol type) { // unbound type parameters might contain null, even though they cannot be *assigned* null. return !type.IsValueType || type.IsNullableTypeOrTypeParameter(); } public static bool CanBeConst(this TypeSymbol typeSymbol) { RoslynDebug.Assert((object)typeSymbol != null); return typeSymbol.IsReferenceType || typeSymbol.IsEnumType() || typeSymbol.SpecialType.CanBeConst() || typeSymbol.IsNativeIntegerType; } /// <summary> /// Assuming that nullable annotations are enabled: /// T => true /// T where T : struct => false /// T where T : class => false /// T where T : class? => true /// T where T : IComparable => true /// T where T : IComparable? => true /// T where T : notnull => true /// </summary> /// <remarks> /// In C#9, annotations are allowed regardless of constraints. /// </remarks> public static bool IsTypeParameterDisallowingAnnotationInCSharp8(this TypeSymbol type) { if (type.TypeKind != TypeKind.TypeParameter) { return false; } var typeParameter = (TypeParameterSymbol)type; // https://github.com/dotnet/roslyn/issues/30056: Test `where T : unmanaged`. See // UninitializedNonNullableFieldTests.TypeParameterConstraints for instance. return !typeParameter.IsValueType && !(typeParameter.IsReferenceType && typeParameter.IsNotNullable == true); } /// <summary> /// Assuming that nullable annotations are enabled: /// T => true /// T where T : struct => false /// T where T : class => false /// T where T : class? => true /// T where T : IComparable => false /// T where T : IComparable? => true /// </summary> public static bool IsPossiblyNullableReferenceTypeTypeParameter(this TypeSymbol type) { return type is TypeParameterSymbol { IsValueType: false, IsNotNullable: false }; } public static bool IsNonNullableValueType(this TypeSymbol typeArgument) { if (!typeArgument.IsValueType) { return false; } return !IsNullableTypeOrTypeParameter(typeArgument); } public static bool IsVoidType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_Void; } public static bool IsNullableTypeOrTypeParameter(this TypeSymbol? type) { if (type is null) { return false; } if (type.TypeKind == TypeKind.TypeParameter) { var constraintTypes = ((TypeParameterSymbol)type).ConstraintTypesNoUseSiteDiagnostics; foreach (var constraintType in constraintTypes) { if (constraintType.Type.IsNullableTypeOrTypeParameter()) { return true; } } return false; } return type.IsNullableType(); } /// <summary> /// Is this System.Nullable`1 type, or its substitution. /// /// To check whether a type is System.Nullable`1 or is a type parameter constrained to System.Nullable`1 /// use <see cref="TypeSymbolExtensions.IsNullableTypeOrTypeParameter" /> instead. /// </summary> public static bool IsNullableType(this TypeSymbol type) { return type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T; } public static bool IsValidNullableTypeArgument(this TypeSymbol type) { return type is { IsValueType: true } && !type.IsNullableType() && !type.IsPointerOrFunctionPointer() && !type.IsRestrictedType(); } public static TypeSymbol GetNullableUnderlyingType(this TypeSymbol type) { return type.GetNullableUnderlyingTypeWithAnnotations().Type; } public static TypeWithAnnotations GetNullableUnderlyingTypeWithAnnotations(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); RoslynDebug.Assert(IsNullableType(type)); RoslynDebug.Assert(type is NamedTypeSymbol); //not testing Kind because it may be an ErrorType return ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; } public static TypeSymbol StrippedType(this TypeSymbol type) { return type.IsNullableType() ? type.GetNullableUnderlyingType() : type; } public static TypeSymbol EnumUnderlyingTypeOrSelf(this TypeSymbol type) { return type.GetEnumUnderlyingType() ?? type; } public static bool IsNativeIntegerOrNullableThereof(this TypeSymbol? type) { return type?.StrippedType().IsNativeIntegerType == true; } public static bool IsObjectType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_Object; } public static bool IsStringType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_String; } public static bool IsCharType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_Char; } public static bool IsIntegralType(this TypeSymbol type) { return type.SpecialType.IsIntegralType(); } public static NamedTypeSymbol? GetEnumUnderlyingType(this TypeSymbol? type) { return (type is NamedTypeSymbol namedType) ? namedType.EnumUnderlyingType : null; } public static bool IsEnumType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Enum; } public static bool IsValidEnumType(this TypeSymbol type) { var underlyingType = type.GetEnumUnderlyingType(); // SpecialType will be None if the underlying type is invalid. return (underlyingType is object) && (underlyingType.SpecialType != SpecialType.None); } /// <summary> /// Determines if the given type is a valid attribute parameter type. /// </summary> /// <param name="type">Type to validated</param> /// <param name="compilation">compilation</param> /// <returns></returns> public static bool IsValidAttributeParameterType(this TypeSymbol type, CSharpCompilation compilation) { return GetAttributeParameterTypedConstantKind(type, compilation) != TypedConstantKind.Error; } /// <summary> /// Gets the typed constant kind for the given attribute parameter type. /// </summary> /// <param name="type">Type to validated</param> /// <param name="compilation">compilation</param> /// <returns>TypedConstantKind for the attribute parameter type.</returns> public static TypedConstantKind GetAttributeParameterTypedConstantKind(this TypeSymbol type, CSharpCompilation compilation) { // Spec (17.1.3) // The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are: // 1) One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort. // 2) The type object. // 3) The type System.Type. // 4) An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility. // 5) Single-dimensional arrays of the above types. // A constructor argument or public field which does not have one of these types, cannot be used as a positional // or named parameter in an attribute specification. TypedConstantKind kind = TypedConstantKind.Error; if ((object)type == null) { return TypedConstantKind.Error; } if (type.Kind == SymbolKind.ArrayType) { var arrayType = (ArrayTypeSymbol)type; if (!arrayType.IsSZArray) { return TypedConstantKind.Error; } kind = TypedConstantKind.Array; type = arrayType.ElementType; } // enum or enum[] if (type.IsEnumType()) { // SPEC VIOLATION: Dev11 doesn't enforce either the Enum type or its enclosing types (if any) to have public accessibility. // We will be consistent with Dev11 behavior. if (kind == TypedConstantKind.Error) { // set only if kind is not already set (i.e. its not an array of enum) kind = TypedConstantKind.Enum; } type = type.GetEnumUnderlyingType()!; } var typedConstantKind = TypedConstant.GetTypedConstantKind(type, compilation); switch (typedConstantKind) { case TypedConstantKind.Array: case TypedConstantKind.Enum: case TypedConstantKind.Error: return TypedConstantKind.Error; default: if (kind == TypedConstantKind.Array || kind == TypedConstantKind.Enum) { // Array/Enum type with valid element/underlying type return kind; } return typedConstantKind; } } public static bool IsValidExtensionParameterType(this TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Pointer: case TypeKind.Dynamic: case TypeKind.FunctionPointer: return false; default: return true; } } public static bool IsInterfaceType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)type).IsInterface; } public static bool IsClassType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Class; } public static bool IsStructType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Struct; } public static bool IsErrorType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.Kind == SymbolKind.ErrorType; } public static bool IsMethodTypeParameter(this TypeParameterSymbol p) { return p.ContainingSymbol.Kind == SymbolKind.Method; } public static bool IsDynamic(this TypeSymbol type) { return type.TypeKind == TypeKind.Dynamic; } public static bool IsTypeParameter(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.TypeParameter; } public static bool IsArray(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Array; } public static bool IsSZArray(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Array && ((ArrayTypeSymbol)type).IsSZArray; } public static bool IsFunctionPointer(this TypeSymbol type) { return type.TypeKind == TypeKind.FunctionPointer; } public static bool IsPointerOrFunctionPointer(this TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Pointer: case TypeKind.FunctionPointer: return true; default: return false; } } // If the type is a delegate type, it returns it. If the type is an // expression tree type associated with a delegate type, it returns // the delegate type. Otherwise, null. public static NamedTypeSymbol? GetDelegateType(this TypeSymbol? type) { if (type is null) return null; if (type.IsExpressionTree()) { type = ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; } return type.IsDelegateType() ? (NamedTypeSymbol)type : null; } public static TypeSymbol? GetDelegateOrFunctionPointerType(this TypeSymbol? type) { return (TypeSymbol?)GetDelegateType(type) ?? type as FunctionPointerTypeSymbol; } /// <summary> /// Returns true if the type is constructed from a generic type named "System.Linq.Expressions.Expression" /// with one type parameter. /// </summary> public static bool IsExpressionTree(this TypeSymbol type) { return type.IsGenericOrNonGenericExpressionType(out bool isGenericType) && isGenericType; } /// <summary> /// Returns true if the type is a non-generic type named "System.Linq.Expressions.Expression" /// or "System.Linq.Expressions.LambdaExpression". /// </summary> public static bool IsNonGenericExpressionType(this TypeSymbol type) { return type.IsGenericOrNonGenericExpressionType(out bool isGenericType) && !isGenericType; } /// <summary> /// Returns true if the type is constructed from a generic type named "System.Linq.Expressions.Expression" /// with one type parameter, or if the type is a non-generic type named "System.Linq.Expressions.Expression" /// or "System.Linq.Expressions.LambdaExpression". /// </summary> public static bool IsGenericOrNonGenericExpressionType(this TypeSymbol _type, out bool isGenericType) { if (_type.OriginalDefinition is NamedTypeSymbol type) { switch (type.Name) { case "Expression": if (IsNamespaceName(type.ContainingSymbol, s_expressionsNamespaceName)) { if (type.Arity == 0) { isGenericType = false; return true; } if (type.Arity == 1 && type.MangleName) { isGenericType = true; return true; } } break; case "LambdaExpression": if (IsNamespaceName(type.ContainingSymbol, s_expressionsNamespaceName) && type.Arity == 0) { isGenericType = false; return true; } break; } } isGenericType = false; return false; } /// <summary> /// return true if the type is constructed from a generic interface that /// might be implemented by an array. /// </summary> public static bool IsPossibleArrayGenericInterface(this TypeSymbol type) { if (!(type is NamedTypeSymbol t)) { return false; } t = t.OriginalDefinition; SpecialType st = t.SpecialType; if (st == SpecialType.System_Collections_Generic_IList_T || st == SpecialType.System_Collections_Generic_ICollection_T || st == SpecialType.System_Collections_Generic_IEnumerable_T || st == SpecialType.System_Collections_Generic_IReadOnlyList_T || st == SpecialType.System_Collections_Generic_IReadOnlyCollection_T) { return true; } return false; } internal static bool IsErrorTypeOrRefLikeType(this TypeSymbol type) { return type.IsErrorType() || type.IsRefLikeType; } private static readonly string[] s_expressionsNamespaceName = { "Expressions", "Linq", MetadataHelpers.SystemString, "" }; private static bool IsNamespaceName(Symbol symbol, string[] names) { if (symbol.Kind != SymbolKind.Namespace) { return false; } for (int i = 0; i < names.Length; i++) { if ((object)symbol == null || symbol.Name != names[i]) return false; symbol = symbol.ContainingSymbol; } return true; } public static bool IsDelegateType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Delegate; } public static ImmutableArray<ParameterSymbol> DelegateParameters(this TypeSymbol type) { var invokeMethod = type.DelegateInvokeMethod(); if (invokeMethod is null) { return default(ImmutableArray<ParameterSymbol>); } return invokeMethod.Parameters; } public static ImmutableArray<ParameterSymbol> DelegateOrFunctionPointerParameters(this TypeSymbol type) { Debug.Assert(type is FunctionPointerTypeSymbol || type.IsDelegateType()); if (type is FunctionPointerTypeSymbol { Signature: { Parameters: var functionPointerParameters } }) { return functionPointerParameters; } else { return type.DelegateParameters(); } } public static bool TryGetElementTypesWithAnnotationsIfTupleType(this TypeSymbol type, out ImmutableArray<TypeWithAnnotations> elementTypes) { if (type.IsTupleType) { elementTypes = ((NamedTypeSymbol)type).TupleElementTypesWithAnnotations; return true; } // source not a tuple elementTypes = default(ImmutableArray<TypeWithAnnotations>); return false; } public static MethodSymbol? DelegateInvokeMethod(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); RoslynDebug.Assert(type.IsDelegateType() || type.IsExpressionTree()); return type.GetDelegateType()!.DelegateInvokeMethod; } /// <summary> /// Return the default value constant for the given type, /// or null if the default value is not a constant. /// </summary> public static ConstantValue? GetDefaultValue(this TypeSymbol type) { // SPEC: A default-value-expression is a constant expression (§7.19) if the type // SPEC: is a reference type or a type parameter that is known to be a reference type (§10.1.5). // SPEC: In addition, a default-value-expression is a constant expression if the type is // SPEC: one of the following value types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or any enumeration type. RoslynDebug.Assert((object)type != null); if (type.IsErrorType()) { return null; } if (type.IsReferenceType) { return ConstantValue.Null; } if (type.IsValueType) { type = type.EnumUnderlyingTypeOrSelf(); switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: case SpecialType.System_Char: case SpecialType.System_Boolean: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: return ConstantValue.Default(type.SpecialType); } } return null; } public static SpecialType GetSpecialTypeSafe(this TypeSymbol? type) { return type is object ? type.SpecialType : SpecialType.None; } public static bool IsAtLeastAsVisibleAs(this TypeSymbol type, Symbol sym, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { CompoundUseSiteInfo<AssemblySymbol> localUseSiteInfo = useSiteInfo; var result = type.VisitType((type1, symbol, unused) => IsTypeLessVisibleThan(type1, symbol, ref localUseSiteInfo), sym, canDigThroughNullable: true); // System.Nullable is public useSiteInfo = localUseSiteInfo; return result is null; } private static bool IsTypeLessVisibleThan(TypeSymbol type, Symbol sym, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (type.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Enum: case TypeKind.Delegate: case TypeKind.Submission: return !IsAsRestrictive((NamedTypeSymbol)type, sym, ref useSiteInfo); default: return false; } } /// <summary> /// Visit the given type and, in the case of compound types, visit all "sub type" /// (such as A in A[], or { A&lt;T&gt;, T, U } in A&lt;T&gt;.B&lt;U&gt;) invoking 'predicate' /// with the type and 'arg' at each sub type. If the predicate returns true for any type, /// traversal stops and that type is returned from this method. Otherwise if traversal /// completes without the predicate returning true for any type, this method returns null. /// </summary> public static TypeSymbol? VisitType<T>( this TypeSymbol type, Func<TypeSymbol, T, bool, bool> predicate, T arg, bool canDigThroughNullable = false, bool visitCustomModifiers = false) { return VisitType( typeWithAnnotationsOpt: default, type: type, typeWithAnnotationsPredicate: null, typePredicate: predicate, arg, canDigThroughNullable, visitCustomModifiers: visitCustomModifiers); } /// <summary> /// Visit the given type and, in the case of compound types, visit all "sub type". /// One of the predicates will be invoked at each type. If the type is a /// TypeWithAnnotations, <paramref name="typeWithAnnotationsPredicate"/> /// will be invoked; otherwise <paramref name="typePredicate"/> will be invoked. /// If the corresponding predicate returns true for any type, /// traversal stops and that type is returned from this method. Otherwise if traversal /// completes without the predicate returning true for any type, this method returns null. /// </summary> /// <param name="useDefaultType">If true, use <see cref="TypeWithAnnotations.DefaultType"/> /// instead of <see cref="TypeWithAnnotations.Type"/> to avoid early resolution of nullable types</param> public static TypeSymbol? VisitType<T>( this TypeWithAnnotations typeWithAnnotationsOpt, TypeSymbol? type, Func<TypeWithAnnotations, T, bool, bool>? typeWithAnnotationsPredicate, Func<TypeSymbol, T, bool, bool>? typePredicate, T arg, bool canDigThroughNullable = false, bool useDefaultType = false, bool visitCustomModifiers = false) { RoslynDebug.Assert(typeWithAnnotationsOpt.HasType == (type is null)); RoslynDebug.Assert(canDigThroughNullable == false || useDefaultType == false, "digging through nullable will cause early resolution of nullable types"); RoslynDebug.Assert(canDigThroughNullable == false || visitCustomModifiers == false); RoslynDebug.Assert(visitCustomModifiers == false || typePredicate is { }); // In order to handle extremely "deep" types like "int[][][][][][][][][]...[]" // or int*****************...* we implement manual tail recursion rather than // doing the natural recursion. while (true) { TypeSymbol current = type ?? (useDefaultType ? typeWithAnnotationsOpt.DefaultType : typeWithAnnotationsOpt.Type); bool isNestedNamedType = false; // Visit containing types from outer-most to inner-most. switch (current.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Enum: case TypeKind.Delegate: { var containingType = current.ContainingType; if ((object)containingType != null) { isNestedNamedType = true; var result = VisitType(default, containingType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); if (result is object) { return result; } } } break; case TypeKind.Submission: RoslynDebug.Assert((object)current.ContainingType == null); break; } if (typeWithAnnotationsOpt.HasType && typeWithAnnotationsPredicate != null) { if (typeWithAnnotationsPredicate(typeWithAnnotationsOpt, arg, isNestedNamedType)) { return current; } } else if (typePredicate != null) { if (typePredicate(current, arg, isNestedNamedType)) { return current; } } if (visitCustomModifiers && typeWithAnnotationsOpt.HasType) { foreach (var customModifier in typeWithAnnotationsOpt.CustomModifiers) { var result = VisitType( typeWithAnnotationsOpt: default, type: ((CSharpCustomModifier)customModifier).ModifierSymbol, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); if (result is object) { return result; } } } TypeWithAnnotations next; switch (current.TypeKind) { case TypeKind.Dynamic: case TypeKind.TypeParameter: case TypeKind.Submission: case TypeKind.Enum: return null; case TypeKind.Error: case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Delegate: if (current.IsAnonymousType) { var anonymous = (AnonymousTypeManager.AnonymousTypeOrDelegatePublicSymbol)current; var fields = anonymous.TypeDescriptor.Fields; if (fields.IsEmpty) { return null; } int i; for (i = 0; i < fields.Length - 1; i++) { // Let's try to avoid early resolution of nullable types (TypeWithAnnotations nextTypeWithAnnotations, TypeSymbol? nextType) = getNextIterationElements(fields[i].TypeWithAnnotations, canDigThroughNullable); var result = VisitType( typeWithAnnotationsOpt: nextTypeWithAnnotations, type: nextType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); if (result is object) { return result; } } next = fields[i].TypeWithAnnotations; } else { var typeArguments = ((NamedTypeSymbol)current).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; if (typeArguments.IsEmpty) { return null; } int i; for (i = 0; i < typeArguments.Length - 1; i++) { // Let's try to avoid early resolution of nullable types (TypeWithAnnotations nextTypeWithAnnotations, TypeSymbol? nextType) = getNextIterationElements(typeArguments[i], canDigThroughNullable); var result = VisitType( typeWithAnnotationsOpt: nextTypeWithAnnotations, type: nextType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); if (result is object) { return result; } } next = typeArguments[i]; } break; case TypeKind.Array: next = ((ArrayTypeSymbol)current).ElementTypeWithAnnotations; break; case TypeKind.Pointer: next = ((PointerTypeSymbol)current).PointedAtTypeWithAnnotations; break; case TypeKind.FunctionPointer: { var result = visitFunctionPointerType((FunctionPointerTypeSymbol)current, typeWithAnnotationsPredicate, typePredicate, arg, useDefaultType, canDigThroughNullable, visitCustomModifiers, out next); if (result is object) { return result; } break; } default: throw ExceptionUtilities.UnexpectedValue(current.TypeKind); } // Let's try to avoid early resolution of nullable types typeWithAnnotationsOpt = canDigThroughNullable ? default : next; type = canDigThroughNullable ? next.NullableUnderlyingTypeOrSelf : null; } static (TypeWithAnnotations, TypeSymbol?) getNextIterationElements(TypeWithAnnotations type, bool canDigThroughNullable) => canDigThroughNullable ? (default(TypeWithAnnotations), type.NullableUnderlyingTypeOrSelf) : (type, null); static TypeSymbol? visitFunctionPointerType(FunctionPointerTypeSymbol type, Func<TypeWithAnnotations, T, bool, bool>? typeWithAnnotationsPredicate, Func<TypeSymbol, T, bool, bool>? typePredicate, T arg, bool useDefaultType, bool canDigThroughNullable, bool visitCustomModifiers, out TypeWithAnnotations next) { MethodSymbol currentPointer = type.Signature; if (currentPointer.ParameterCount == 0) { next = currentPointer.ReturnTypeWithAnnotations; return null; } var result = VisitType( typeWithAnnotationsOpt: canDigThroughNullable ? default : currentPointer.ReturnTypeWithAnnotations, type: canDigThroughNullable ? currentPointer.ReturnTypeWithAnnotations.NullableUnderlyingTypeOrSelf : null, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); if (result is object) { next = default; return result; } int i; for (i = 0; i < currentPointer.ParameterCount - 1; i++) { (TypeWithAnnotations nextTypeWithAnnotations, TypeSymbol? nextType) = getNextIterationElements(currentPointer.Parameters[i].TypeWithAnnotations, canDigThroughNullable); result = VisitType( typeWithAnnotationsOpt: nextTypeWithAnnotations, type: nextType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); if (result is object) { next = default; return result; } } next = currentPointer.Parameters[i].TypeWithAnnotations; return null; } } internal static bool IsAsRestrictive(this Symbol s1, Symbol sym2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Accessibility acc1 = s1.DeclaredAccessibility; if (acc1 == Accessibility.Public) { return true; } for (Symbol s2 = sym2; s2.Kind != SymbolKind.Namespace; s2 = s2.ContainingSymbol) { Accessibility acc2 = s2.DeclaredAccessibility; switch (acc1) { case Accessibility.Internal: { // If s2 is private or internal, and within the same assembly as s1, // then this is at least as restrictive as s1's internal. if ((acc2 == Accessibility.Private || acc2 == Accessibility.Internal || acc2 == Accessibility.ProtectedAndInternal) && s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { return true; } break; } case Accessibility.ProtectedAndInternal: // Since s1 is private protected, s2 must pass the test for being both more restrictive than internal and more restrictive than protected. // We first do the "internal" test (copied from above), then if it passes we continue with the "protected" test. if ((acc2 == Accessibility.Private || acc2 == Accessibility.Internal || acc2 == Accessibility.ProtectedAndInternal) && s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { // passed the internal test; now do the test for the protected case goto case Accessibility.Protected; } break; case Accessibility.Protected: { var parent1 = s1.ContainingType; if ((object)parent1 == null) { // not helpful } else if (acc2 == Accessibility.Private) { // if s2 is private and within s1's parent or within a subclass of s1's parent, // then this is at least as restrictive as s1's protected. for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType) { if (parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo)) { return true; } } } else if (acc2 == Accessibility.Protected || acc2 == Accessibility.ProtectedAndInternal) { // if s2 is protected, and it's parent is a subclass (or the same as) s1's parent // then this is at least as restrictive as s1's protected var parent2 = s2.ContainingType; if ((object)parent2 != null && parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo)) { return true; } } break; } case Accessibility.ProtectedOrInternal: { var parent1 = s1.ContainingType; if ((object)parent1 == null) { break; } switch (acc2) { case Accessibility.Private: // if s2 is private and within a subclass of s1's parent, // or within the same assembly as s1 // then this is at least as restrictive as s1's internal protected. if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { return true; } for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType) { if (parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo)) { return true; } } break; case Accessibility.Internal: // If s2 is in the same assembly as s1, then this is more restrictive // than s1's internal protected. if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { return true; } break; case Accessibility.Protected: // if s2 is protected, and it's parent is a subclass (or the same as) s1's parent // then this is at least as restrictive as s1's internal protected if (parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo)) { return true; } break; case Accessibility.ProtectedAndInternal: // if s2 is private protected, and it's parent is a subclass (or the same as) s1's parent // or its in the same assembly as s1, then this is at least as restrictive as s1's protected if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly) || parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo)) { return true; } break; case Accessibility.ProtectedOrInternal: // if s2 is internal protected, and it's parent is a subclass (or the same as) s1's parent // and its in the same assembly as s1, then this is at least as restrictive as s1's protected if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly) && parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo)) { return true; } break; } break; } case Accessibility.Private: if (acc2 == Accessibility.Private) { // if s2 is private, and it is within s1's parent, then this is at // least as restrictive as s1's private. NamedTypeSymbol parent1 = s1.ContainingType; if ((object)parent1 == null) { break; } var parent1OriginalDefinition = parent1.OriginalDefinition; for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType) { if (ReferenceEquals(parent2.OriginalDefinition, parent1OriginalDefinition) || parent1OriginalDefinition.TypeKind == TypeKind.Submission && parent2.TypeKind == TypeKind.Submission) { return true; } } } break; default: throw ExceptionUtilities.UnexpectedValue(acc1); } } return false; } public static bool IsUnboundGenericType(this TypeSymbol type) { return type is NamedTypeSymbol { IsUnboundGenericType: true }; } public static bool IsTopLevelType(this NamedTypeSymbol type) { return (object)type.ContainingType == null; } /// <summary> /// (null TypeParameterSymbol "parameter"): Checks if the given type is a type parameter /// or its referent type is a type parameter (array/pointer) or contains a type parameter (aggregate type) /// (non-null TypeParameterSymbol "parameter"): above + also checks if the type parameter /// is the same as "parameter" /// </summary> public static bool ContainsTypeParameter(this TypeSymbol type, TypeParameterSymbol? parameter = null) { var result = type.VisitType(s_containsTypeParameterPredicate, parameter); return result is object; } private static readonly Func<TypeSymbol, TypeParameterSymbol?, bool, bool> s_containsTypeParameterPredicate = (type, parameter, unused) => type.TypeKind == TypeKind.TypeParameter && (parameter is null || TypeSymbol.Equals(type, parameter, TypeCompareKind.ConsiderEverything2)); public static bool ContainsTypeParameter(this TypeSymbol type, MethodSymbol parameterContainer) { RoslynDebug.Assert((object)parameterContainer != null); var result = type.VisitType(s_isTypeParameterWithSpecificContainerPredicate, parameterContainer); return result is object; } private static readonly Func<TypeSymbol, Symbol, bool, bool> s_isTypeParameterWithSpecificContainerPredicate = (type, parameterContainer, unused) => type.TypeKind == TypeKind.TypeParameter && (object)type.ContainingSymbol == (object)parameterContainer; public static bool ContainsTypeParameters(this TypeSymbol type, HashSet<TypeParameterSymbol> parameters) { var result = type.VisitType(s_containsTypeParametersPredicate, parameters); return result is object; } private static readonly Func<TypeSymbol, HashSet<TypeParameterSymbol>, bool, bool> s_containsTypeParametersPredicate = (type, parameters, unused) => type.TypeKind == TypeKind.TypeParameter && parameters.Contains((TypeParameterSymbol)type); public static bool ContainsMethodTypeParameter(this TypeSymbol type) { var result = type.VisitType(s_containsMethodTypeParameterPredicate, null); return result is object; } private static readonly Func<TypeSymbol, object?, bool, bool> s_containsMethodTypeParameterPredicate = (type, _, _) => type.TypeKind == TypeKind.TypeParameter && type.ContainingSymbol is MethodSymbol; /// <summary> /// Return true if the type contains any dynamic type reference. /// </summary> public static bool ContainsDynamic(this TypeSymbol type) { var result = type.VisitType(s_containsDynamicPredicate, null, canDigThroughNullable: true); return result is object; } private static readonly Func<TypeSymbol, object?, bool, bool> s_containsDynamicPredicate = (type, unused1, unused2) => type.TypeKind == TypeKind.Dynamic; internal static bool ContainsNativeIntegerWrapperType(this TypeSymbol type) { var result = type.VisitType((type, unused1, unused2) => type.IsNativeIntegerWrapperType, (object?)null, canDigThroughNullable: true); return result is object; } internal static bool ContainsNativeIntegerWrapperType(this TypeWithAnnotations type) { return type.Type?.ContainsNativeIntegerWrapperType() == true; } internal static bool ContainsErrorType(this TypeSymbol type) { var result = type.VisitType((type, unused1, unused2) => type.IsErrorType(), (object?)null, canDigThroughNullable: true); return result is object; } /// <summary> /// Return true if the type contains any tuples. /// </summary> internal static bool ContainsTuple(this TypeSymbol type) => type.VisitType((TypeSymbol t, object? _1, bool _2) => t.IsTupleType, null) is object; /// <summary> /// Return true if the type contains any tuples with element names. /// </summary> internal static bool ContainsTupleNames(this TypeSymbol type) => type.VisitType((TypeSymbol t, object? _1, bool _2) => !t.TupleElementNames.IsDefault, null) is object; /// <summary> /// Return true if the type contains any function pointer types. /// </summary> internal static bool ContainsFunctionPointer(this TypeSymbol type) => type.VisitType((TypeSymbol t, object? _, bool _) => t.IsFunctionPointer(), null) is object; /// <summary> /// Guess the non-error type that the given type was intended to represent. /// If the type itself is not an error type, then it will be returned. /// Otherwise, the underlying type (if any) of the error type will be /// returned. /// </summary> /// <remarks> /// Any non-null type symbol returned is guaranteed not to be an error type. /// /// It is possible to pass in a constructed type and received back an /// unconstructed type. This can occur when the type passed in was /// constructed from an error type - the underlying definition will be /// available, but there won't be a good way to "re-substitute" back up /// to the level of the specified type. /// </remarks> internal static TypeSymbol? GetNonErrorGuess(this TypeSymbol type) { var result = ExtendedErrorTypeSymbol.ExtractNonErrorType(type); RoslynDebug.Assert((object?)result == null || !result.IsErrorType()); return result; } /// <summary> /// Guess the non-error type kind that the given type was intended to represent, /// if possible. If not, return TypeKind.Error. /// </summary> internal static TypeKind GetNonErrorTypeKindGuess(this TypeSymbol type) { return ExtendedErrorTypeSymbol.ExtractNonErrorTypeKind(type); } /// <summary> /// Returns true if the type was a valid switch expression type in C# 6. We use this test to determine /// whether or not we should attempt a user-defined conversion from the type to a C# 6 switch governing /// type, which we support for compatibility with C# 6 and earlier. /// </summary> internal static bool IsValidV6SwitchGoverningType(this TypeSymbol type, bool isTargetTypeOfUserDefinedOp = false) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types RoslynDebug.Assert((object)type != null); if (type.IsNullableType()) { type = type.GetNullableUnderlyingType(); } // User-defined implicit conversion with target type as Enum type is not valid. if (!isTargetTypeOfUserDefinedOp) { type = type.EnumUnderlyingTypeOrSelf(); } switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Char: case SpecialType.System_String: return true; case SpecialType.System_Boolean: // User-defined implicit conversion with target type as bool type is not valid. return !isTargetTypeOfUserDefinedOp; } return false; } internal static bool IsSpanChar(this TypeSymbol type) { return type is NamedTypeSymbol { ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, MetadataName: "Span`1", TypeArgumentsWithAnnotationsNoUseSiteDiagnostics: { Length: 1 } arguments, } && arguments[0].SpecialType == SpecialType.System_Char; } internal static bool IsReadOnlySpanChar(this TypeSymbol type) { return type is NamedTypeSymbol { ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, MetadataName: "ReadOnlySpan`1", TypeArgumentsWithAnnotationsNoUseSiteDiagnostics: { Length: 1 } arguments, } && arguments[0].SpecialType == SpecialType.System_Char; } internal static bool IsSpanOrReadOnlySpanChar(this TypeSymbol type) { return type is NamedTypeSymbol { ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, MetadataName: "ReadOnlySpan`1" or "Span`1", TypeArgumentsWithAnnotationsNoUseSiteDiagnostics: { Length: 1 } arguments, } && arguments[0].SpecialType == SpecialType.System_Char; } #pragma warning disable CA1200 // Avoid using cref tags with a prefix /// <summary> /// Returns true if the type is one of the restricted types, namely: <see cref="T:System.TypedReference"/>, /// <see cref="T:System.ArgIterator"/>, or <see cref="T:System.RuntimeArgumentHandle"/>. /// or a ref-like type. /// </summary> #pragma warning restore CA1200 // Avoid using cref tags with a prefix internal static bool IsRestrictedType(this TypeSymbol type, bool ignoreSpanLikeTypes = false) { // See Dev10 C# compiler, "type.cpp", bool Type::isSpecialByRefType() const RoslynDebug.Assert((object)type != null); switch (type.SpecialType) { case SpecialType.System_TypedReference: case SpecialType.System_ArgIterator: case SpecialType.System_RuntimeArgumentHandle: return true; } return ignoreSpanLikeTypes ? false : type.IsRefLikeType; } public static bool IsIntrinsicType(this TypeSymbol type) { switch (type.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_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: case SpecialType.System_Single: case SpecialType.System_Double: // NOTE: VB treats System.DateTime as an intrinsic, while C# does not. //case SpecialType.System_DateTime: case SpecialType.System_Decimal: return true; default: return false; } } public static bool IsPartial(this TypeSymbol type) { return type is SourceNamedTypeSymbol { IsPartial: true }; } public static bool IsFileTypeOrUsesFileTypes(this TypeSymbol type) { var foundType = type.VisitType(predicate: (type, _, _) => type is SourceMemberContainerTypeSymbol { IsFile: true }, arg: (object?)null); return foundType is not null; } internal static string? AssociatedFileIdentifier(this NamedTypeSymbol type) { if (type.AssociatedSyntaxTree is not SyntaxTree tree) { return null; } var ordinal = type.DeclaringCompilation.GetSyntaxTreeOrdinal(tree); return GeneratedNames.MakeFileIdentifier(tree.FilePath, ordinal); } public static bool IsPointerType(this TypeSymbol type) { return type is PointerTypeSymbol; } internal static int FixedBufferElementSizeInBytes(this TypeSymbol type) { return type.SpecialType.FixedBufferElementSizeInBytes(); } // check that its type is allowed for Volatile internal static bool IsValidVolatileFieldType(this TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Struct: return type.SpecialType.IsValidVolatileFieldType(); case TypeKind.Array: case TypeKind.Class: case TypeKind.Delegate: case TypeKind.Dynamic: case TypeKind.Error: case TypeKind.Interface: case TypeKind.Pointer: case TypeKind.FunctionPointer: return true; case TypeKind.Enum: return ((NamedTypeSymbol)type).EnumUnderlyingType.SpecialType.IsValidVolatileFieldType(); case TypeKind.TypeParameter: return type.IsReferenceType; case TypeKind.Submission: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } return false; } /// <summary> /// Add this instance to the set of checked types. Returns true /// if this was added, false if the type was already in the set. /// </summary> public static bool MarkCheckedIfNecessary(this TypeSymbol type, ref HashSet<TypeSymbol> checkedTypes) { if (checkedTypes == null) { checkedTypes = new HashSet<TypeSymbol>(); } return checkedTypes.Add(type); } internal static bool IsUnsafe(this TypeSymbol type) { while (true) { switch (type.TypeKind) { case TypeKind.Pointer: case TypeKind.FunctionPointer: return true; case TypeKind.Array: type = ((ArrayTypeSymbol)type).ElementType; break; default: // NOTE: we could consider a generic type with unsafe type arguments to be unsafe, // but that's already an error, so there's no reason to report it. Also, this // matches Type::isUnsafe in Dev10. return false; } } } internal static bool IsVoidPointer(this TypeSymbol type) { return type is PointerTypeSymbol p && p.PointedAtType.IsVoidType(); } /// <summary> /// These special types are structs that contain fields of the same type /// (e.g. <see cref="System.Int32"/> contains an instance field of type <see cref="System.Int32"/>). /// </summary> internal static bool IsPrimitiveRecursiveStruct(this TypeSymbol t) { return t.SpecialType.IsPrimitiveRecursiveStruct(); } /// <summary> /// Compute a hash code for the constructed type. The return value will be /// non-zero so callers can used zero to represent an uninitialized value. /// </summary> internal static int ComputeHashCode(this NamedTypeSymbol type) { RoslynDebug.Assert(!type.Equals(type.OriginalDefinition, TypeCompareKind.AllIgnoreOptions) || wasConstructedForAnnotations(type)); if (wasConstructedForAnnotations(type)) { // A type that uses its own type parameters as type arguments was constructed only for the purpose of adding annotations. // In that case we'll use the hash from the definition. return type.OriginalDefinition.GetHashCode(); } int code = type.OriginalDefinition.GetHashCode(); code = Hash.Combine(type.ContainingType, code); // Unconstructed type may contain alpha-renamed type parameters while // may still be considered equal, we do not want to give different hashcode to such types. // // Example: // Having original type A<U>.B<V> we create two _unconstructed_ types // A<int>.B<V'> // A<int>.B<V"> // Note that V' and V" are type parameters substituted via alpha-renaming of original V // These are different objects, but represent the same "type parameter at index 1" // // In short - we are not interested in the type parameters of unconstructed types. if ((object)type.ConstructedFrom != (object)type) { foreach (var arg in type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { code = Hash.Combine(arg.Type, code); } } // 0 may be used by the caller to indicate the hashcode is not // initialized. If we computed 0 for the hashcode, tweak it. if (code == 0) { code++; } return code; static bool wasConstructedForAnnotations(NamedTypeSymbol type) { do { var typeArguments = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var typeParameters = type.OriginalDefinition.TypeParameters; for (int i = 0; i < typeArguments.Length; i++) { if (!typeParameters[i].Equals( typeArguments[i].Type.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { return false; } } type = type.ContainingType; } while (type is object && !type.IsDefinition); return true; } } /// <summary> /// If we are in a COM PIA with embedInteropTypes enabled we should turn properties and methods /// that have the type and return type of object, respectively, into type dynamic. If the requisite conditions /// are fulfilled, this method returns a dynamic type. If not, it returns the original type. /// </summary> /// <param name="type">A property type or method return type to be checked for dynamification.</param> /// <param name="containingType">Containing type.</param> /// <returns></returns> public static TypeSymbol AsDynamicIfNoPia(this TypeSymbol type, NamedTypeSymbol containingType) { return type.TryAsDynamicIfNoPia(containingType, out TypeSymbol? result) ? result : type; } public static bool TryAsDynamicIfNoPia(this TypeSymbol type, NamedTypeSymbol containingType, [NotNullWhen(true)] out TypeSymbol? result) { if (type.SpecialType == SpecialType.System_Object) { AssemblySymbol assembly = containingType.ContainingAssembly; if ((object)assembly != null && assembly.IsLinked && containingType.IsComImport) { result = DynamicTypeSymbol.Instance; return true; } } result = null; return false; } /// <summary> /// Type variables are never considered reference types by the verifier. /// </summary> internal static bool IsVerifierReference(this TypeSymbol type) { return type.IsReferenceType && type.TypeKind != TypeKind.TypeParameter; } /// <summary> /// Type variables are never considered value types by the verifier. /// </summary> internal static bool IsVerifierValue(this TypeSymbol type) { return type.IsValueType && type.TypeKind != TypeKind.TypeParameter; } /// <summary> /// Return all of the type parameters in this type and enclosing types, /// from outer-most to inner-most type. /// </summary> internal static ImmutableArray<TypeParameterSymbol> GetAllTypeParameters(this NamedTypeSymbol type) { // Avoid allocating a builder in the common case. if ((object)type.ContainingType == null) { return type.TypeParameters; } var builder = ArrayBuilder<TypeParameterSymbol>.GetInstance(); type.GetAllTypeParameters(builder); return builder.ToImmutableAndFree(); } /// <summary> /// Return all of the type parameters in this type and enclosing types, /// from outer-most to inner-most type. /// </summary> internal static void GetAllTypeParameters(this NamedTypeSymbol type, ArrayBuilder<TypeParameterSymbol> result) { var containingType = type.ContainingType; if ((object)containingType != null) { containingType.GetAllTypeParameters(result); } result.AddRange(type.TypeParameters); } /// <summary> /// Return the nearest type parameter with the given name in /// this type or any enclosing type. /// </summary> internal static TypeParameterSymbol? FindEnclosingTypeParameter(this NamedTypeSymbol type, string name) { var allTypeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); type.GetAllTypeParameters(allTypeParameters); TypeParameterSymbol? result = null; foreach (TypeParameterSymbol tpEnclosing in allTypeParameters) { if (name == tpEnclosing.Name) { result = tpEnclosing; break; } } allTypeParameters.Free(); return result; } /// <summary> /// Return the nearest type parameter with the given name in /// this symbol or any enclosing symbol. /// </summary> internal static TypeParameterSymbol? FindEnclosingTypeParameter(this Symbol methodOrType, string name) { while (methodOrType != null) { switch (methodOrType.Kind) { case SymbolKind.Method: case SymbolKind.NamedType: case SymbolKind.ErrorType: case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: break; default: return null; } foreach (var typeParameter in methodOrType.GetMemberTypeParameters()) { if (typeParameter.Name == name) { return typeParameter; } } methodOrType = methodOrType.ContainingSymbol; } return null; } /// <summary> /// Return true if the fully qualified name of the type's containing symbol /// matches the given name. This method avoids string concatenations /// in the common case where the type is a top-level type. /// </summary> internal static bool HasNameQualifier(this NamedTypeSymbol type, string qualifiedName) { const StringComparison comparison = StringComparison.Ordinal; var container = type.ContainingSymbol; if (container.Kind != SymbolKind.Namespace) { // Nested type. For simplicity, compare qualified name to SymbolDisplay result. return string.Equals(container.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), qualifiedName, comparison); } var @namespace = (NamespaceSymbol)container; if (@namespace.IsGlobalNamespace) { return qualifiedName.Length == 0; } return HasNamespaceName(@namespace, qualifiedName, comparison, length: qualifiedName.Length); } private static bool HasNamespaceName(NamespaceSymbol @namespace, string namespaceName, StringComparison comparison, int length) { if (length == 0) { return false; } var container = @namespace.ContainingNamespace; int separator = namespaceName.LastIndexOf('.', length - 1, length); int offset = 0; if (separator >= 0) { if (container.IsGlobalNamespace) { return false; } if (!HasNamespaceName(container, namespaceName, comparison, length: separator)) { return false; } int n = separator + 1; offset = n; length -= n; } else if (!container.IsGlobalNamespace) { return false; } var name = @namespace.Name; return (name.Length == length) && (string.Compare(name, 0, namespaceName, offset, length, comparison) == 0); } internal static bool IsNonGenericTaskType(this TypeSymbol type, CSharpCompilation compilation) { var namedType = type as NamedTypeSymbol; if (namedType is null || namedType.Arity != 0) { return false; } if ((object)namedType == compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task)) { return true; } if (namedType.IsVoidType()) { return false; } return namedType.IsCustomTaskType(builderArgument: out _); } internal static bool IsGenericTaskType(this TypeSymbol type, CSharpCompilation compilation) { if (!(type is NamedTypeSymbol { Arity: 1 } namedType)) { return false; } if ((object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T)) { return true; } return namedType.IsCustomTaskType(builderArgument: out _); } internal static bool IsIAsyncEnumerableType(this TypeSymbol type, CSharpCompilation compilation) { if (!(type is NamedTypeSymbol { Arity: 1 } namedType)) { return false; } return (object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T); } internal static bool IsIAsyncEnumeratorType(this TypeSymbol type, CSharpCompilation compilation) { if (!(type is NamedTypeSymbol { Arity: 1 } namedType)) { return false; } return (object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T); } /// <summary> /// Returns true if the type is generic or non-generic custom task-like type due to the /// [AsyncMethodBuilder(typeof(B))] attribute. It returns the "B". /// </summary> /// <remarks> /// For the Task types themselves, this method might return true or false depending on mscorlib. /// The definition of "custom task-like type" is one that has an [AsyncMethodBuilder(typeof(B))] attribute, /// no more, no less. Validation of builder type B is left for elsewhere. This method returns B /// without validation of any kind. /// </remarks> internal static bool IsCustomTaskType(this NamedTypeSymbol type, [NotNullWhen(true)] out object? builderArgument) { RoslynDebug.Assert((object)type != null); var arity = type.Arity; if (arity < 2) { return type.HasAsyncMethodBuilderAttribute(out builderArgument); } builderArgument = null; return false; } /// <summary> /// Replace Task-like types with Task types. /// </summary> internal static TypeSymbol NormalizeTaskTypes(this TypeSymbol type, CSharpCompilation compilation) { NormalizeTaskTypesInType(compilation, ref type); return type; } /// <summary> /// Replace Task-like types with Task types. Returns true if there were changes. /// </summary> private static bool NormalizeTaskTypesInType(CSharpCompilation compilation, ref TypeSymbol type) { switch (type.Kind) { case SymbolKind.NamedType: case SymbolKind.ErrorType: { var namedType = (NamedTypeSymbol)type; var changed = NormalizeTaskTypesInNamedType(compilation, ref namedType); type = namedType; return changed; } case SymbolKind.ArrayType: { var arrayType = (ArrayTypeSymbol)type; var changed = NormalizeTaskTypesInArray(compilation, ref arrayType); type = arrayType; return changed; } case SymbolKind.PointerType: { var pointerType = (PointerTypeSymbol)type; var changed = NormalizeTaskTypesInPointer(compilation, ref pointerType); type = pointerType; return changed; } case SymbolKind.FunctionPointerType: { var functionPointerType = (FunctionPointerTypeSymbol)type; var changed = NormalizeTaskTypesInFunctionPointer(compilation, ref functionPointerType); type = functionPointerType; return changed; } } return false; } private static bool NormalizeTaskTypesInType(CSharpCompilation compilation, ref TypeWithAnnotations typeWithAnnotations) { var type = typeWithAnnotations.Type; if (NormalizeTaskTypesInType(compilation, ref type)) { typeWithAnnotations = TypeWithAnnotations.Create(type, customModifiers: typeWithAnnotations.CustomModifiers); return true; } return false; } private static bool NormalizeTaskTypesInNamedType(CSharpCompilation compilation, ref NamedTypeSymbol type) { bool hasChanged = false; if (!type.IsDefinition) { RoslynDebug.Assert(type.IsGenericType); var typeArgumentsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; type.GetAllTypeArguments(typeArgumentsBuilder, ref discardedUseSiteInfo); for (int i = 0; i < typeArgumentsBuilder.Count; i++) { var typeWithModifier = typeArgumentsBuilder[i]; var typeArgNormalized = typeWithModifier.Type; if (NormalizeTaskTypesInType(compilation, ref typeArgNormalized)) { hasChanged = true; // Preserve custom modifiers but without normalizing those types. typeArgumentsBuilder[i] = TypeWithAnnotations.Create(typeArgNormalized, customModifiers: typeWithModifier.CustomModifiers); } } if (hasChanged) { var originalType = type; var originalDefinition = originalType.OriginalDefinition; var typeParameters = originalDefinition.GetAllTypeParameters(); var typeMap = new TypeMap(typeParameters, typeArgumentsBuilder.ToImmutable(), allowAlpha: true); type = typeMap.SubstituteNamedType(originalDefinition).WithTupleDataFrom(originalType); } typeArgumentsBuilder.Free(); } if (type.OriginalDefinition.IsCustomTaskType(builderArgument: out _)) { int arity = type.Arity; RoslynDebug.Assert(arity < 2); var taskType = compilation.GetWellKnownType( arity == 0 ? WellKnownType.System_Threading_Tasks_Task : WellKnownType.System_Threading_Tasks_Task_T); if (taskType.TypeKind == TypeKind.Error) { // Skip if Task types are not available. return false; } type = arity == 0 ? taskType : taskType.Construct( ImmutableArray.Create(type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]), unbound: false); hasChanged = true; } return hasChanged; } private static bool NormalizeTaskTypesInArray(CSharpCompilation compilation, ref ArrayTypeSymbol arrayType) { var elementType = arrayType.ElementTypeWithAnnotations; if (!NormalizeTaskTypesInType(compilation, ref elementType)) { return false; } arrayType = arrayType.WithElementType(elementType); return true; } private static bool NormalizeTaskTypesInPointer(CSharpCompilation compilation, ref PointerTypeSymbol pointerType) { var pointedAtType = pointerType.PointedAtTypeWithAnnotations; if (!NormalizeTaskTypesInType(compilation, ref pointedAtType)) { return false; } // Preserve custom modifiers but without normalizing those types. pointerType = new PointerTypeSymbol(pointedAtType); return true; } private static bool NormalizeTaskTypesInFunctionPointer(CSharpCompilation compilation, ref FunctionPointerTypeSymbol funcPtrType) { var returnType = funcPtrType.Signature.ReturnTypeWithAnnotations; var madeChanges = NormalizeTaskTypesInType(compilation, ref returnType); var paramTypes = ImmutableArray<TypeWithAnnotations>.Empty; if (funcPtrType.Signature.ParameterCount > 0) { var paramsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(funcPtrType.Signature.ParameterCount); bool madeParamChanges = false; foreach (var param in funcPtrType.Signature.Parameters) { var paramType = param.TypeWithAnnotations; madeParamChanges |= NormalizeTaskTypesInType(compilation, ref paramType); paramsBuilder.Add(paramType); } if (madeParamChanges) { madeChanges = true; paramTypes = paramsBuilder.ToImmutableAndFree(); } else { paramTypes = funcPtrType.Signature.ParameterTypesWithAnnotations; paramsBuilder.Free(); } } if (madeChanges) { funcPtrType = funcPtrType.SubstituteTypeSymbol(returnType, paramTypes, refCustomModifiers: default, paramRefCustomModifiers: default); return true; } else { return false; } } internal static Cci.TypeReferenceWithAttributes GetTypeRefWithAttributes( this TypeWithAnnotations type, Emit.PEModuleBuilder moduleBuilder, Symbol declaringSymbol, Cci.ITypeReference typeRef) { var builder = ArrayBuilder<Cci.ICustomAttribute>.GetInstance(); var compilation = declaringSymbol.DeclaringCompilation; if (compilation != null) { if (type.Type.ContainsTupleNames()) { addIfNotNull(builder, compilation.SynthesizeTupleNamesAttribute(type.Type)); } if (compilation.ShouldEmitNativeIntegerAttributes(type.Type)) { addIfNotNull(builder, moduleBuilder.SynthesizeNativeIntegerAttribute(declaringSymbol, type.Type)); } if (compilation.ShouldEmitNullableAttributes(declaringSymbol)) { addIfNotNull(builder, moduleBuilder.SynthesizeNullableAttributeIfNecessary(declaringSymbol, declaringSymbol.GetNullableContextValue(), type)); } static void addIfNotNull(ArrayBuilder<Cci.ICustomAttribute> builder, SynthesizedAttributeData? attr) { if (attr != null) { builder.Add(attr); } } } return new Cci.TypeReferenceWithAttributes(typeRef, builder.ToImmutableAndFree()); } internal static bool IsWellKnownTypeInAttribute(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownInteropServicesTopLevelType("InAttribute"); internal static bool IsWellKnownTypeUnmanagedType(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownInteropServicesTopLevelType("UnmanagedType"); internal static bool IsWellKnownTypeIsExternalInit(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownCompilerServicesTopLevelType("IsExternalInit"); internal static bool IsWellKnownTypeOutAttribute(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownInteropServicesTopLevelType("OutAttribute"); private static bool IsWellKnownInteropServicesTopLevelType(this TypeSymbol typeSymbol, string name) { if (typeSymbol.Name != name || typeSymbol.ContainingType is object) { return false; } return IsContainedInNamespace(typeSymbol, "System", "Runtime", "InteropServices"); } private static bool IsWellKnownCompilerServicesTopLevelType(this TypeSymbol typeSymbol, string name) { if (typeSymbol.Name != name) { return false; } return IsCompilerServicesTopLevelType(typeSymbol); } internal static bool IsCompilerServicesTopLevelType(this TypeSymbol typeSymbol) => typeSymbol.ContainingType is null && IsContainedInNamespace(typeSymbol, "System", "Runtime", "CompilerServices"); internal static bool IsWellKnownSetsRequiredMembersAttribute(this TypeSymbol type) => type.Name == "SetsRequiredMembersAttribute" && type.IsWellKnownDiagnosticsCodeAnalysisTopLevelType(); private static bool IsWellKnownDiagnosticsCodeAnalysisTopLevelType(this TypeSymbol typeSymbol) => typeSymbol.ContainingType is null && IsContainedInNamespace(typeSymbol, "System", "Diagnostics", "CodeAnalysis"); private static bool IsContainedInNamespace(this TypeSymbol typeSymbol, string outerNS, string midNS, string innerNS) { var innerNamespace = typeSymbol.ContainingNamespace; if (innerNamespace?.Name != innerNS) { return false; } var midNamespace = innerNamespace.ContainingNamespace; if (midNamespace?.Name != midNS) { return false; } var outerNamespace = midNamespace.ContainingNamespace; if (outerNamespace?.Name != outerNS) { return false; } var globalNamespace = outerNamespace.ContainingNamespace; return globalNamespace != null && globalNamespace.IsGlobalNamespace; } internal static int TypeToIndex(this TypeSymbol type) { switch (type.GetSpecialTypeSafe()) { case SpecialType.System_Object: return 0; case SpecialType.System_String: return 1; case SpecialType.System_Boolean: return 2; case SpecialType.System_Char: return 3; case SpecialType.System_SByte: return 4; case SpecialType.System_Int16: return 5; case SpecialType.System_Int32: return 6; case SpecialType.System_Int64: return 7; case SpecialType.System_Byte: return 8; case SpecialType.System_UInt16: return 9; case SpecialType.System_UInt32: return 10; case SpecialType.System_UInt64: return 11; case SpecialType.System_IntPtr when type.IsNativeIntegerType: return 12; case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return 13; case SpecialType.System_Single: return 14; case SpecialType.System_Double: return 15; case SpecialType.System_Decimal: return 16; case SpecialType.None: if ((object)type != null && type.IsNullableType()) { TypeSymbol underlyingType = type.GetNullableUnderlyingType(); switch (underlyingType.GetSpecialTypeSafe()) { case SpecialType.System_Boolean: return 17; case SpecialType.System_Char: return 18; case SpecialType.System_SByte: return 19; case SpecialType.System_Int16: return 20; case SpecialType.System_Int32: return 21; case SpecialType.System_Int64: return 22; case SpecialType.System_Byte: return 23; case SpecialType.System_UInt16: return 24; case SpecialType.System_UInt32: return 25; case SpecialType.System_UInt64: return 26; case SpecialType.System_IntPtr when underlyingType.IsNativeIntegerType: return 27; case SpecialType.System_UIntPtr when underlyingType.IsNativeIntegerType: return 28; case SpecialType.System_Single: return 29; case SpecialType.System_Double: return 30; case SpecialType.System_Decimal: return 31; } } // fall through goto default; default: return -1; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static partial class TypeSymbolExtensions { public static bool ImplementsInterface(this TypeSymbol subType, TypeSymbol superInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { foreach (NamedTypeSymbol @interface in subType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (@interface.IsInterface && TypeSymbol.Equals(@interface, superInterface, TypeCompareKind.ConsiderEverything2)) { return true; } } return false; } public static bool CanBeAssignedNull(this TypeSymbol type) { return type.IsReferenceType || type.IsPointerOrFunctionPointer() || type.IsNullableType(); } public static bool CanContainNull(this TypeSymbol type) { // unbound type parameters might contain null, even though they cannot be *assigned* null. return !type.IsValueType || type.IsNullableTypeOrTypeParameter(); } public static bool CanBeConst(this TypeSymbol typeSymbol) { RoslynDebug.Assert((object)typeSymbol != null); return typeSymbol.IsReferenceType || typeSymbol.IsEnumType() || typeSymbol.SpecialType.CanBeConst() || typeSymbol.IsNativeIntegerType; } /// <summary> /// Assuming that nullable annotations are enabled: /// T => true /// T where T : struct => false /// T where T : class => false /// T where T : class? => true /// T where T : IComparable => true /// T where T : IComparable? => true /// T where T : notnull => true /// </summary> /// <remarks> /// In C#9, annotations are allowed regardless of constraints. /// </remarks> public static bool IsTypeParameterDisallowingAnnotationInCSharp8(this TypeSymbol type) { if (type.TypeKind != TypeKind.TypeParameter) { return false; } var typeParameter = (TypeParameterSymbol)type; // https://github.com/dotnet/roslyn/issues/30056: Test `where T : unmanaged`. See // UninitializedNonNullableFieldTests.TypeParameterConstraints for instance. return !typeParameter.IsValueType && !(typeParameter.IsReferenceType && typeParameter.IsNotNullable == true); } /// <summary> /// Assuming that nullable annotations are enabled: /// T => true /// T where T : struct => false /// T where T : class => false /// T where T : class? => true /// T where T : IComparable => false /// T where T : IComparable? => true /// </summary> public static bool IsPossiblyNullableReferenceTypeTypeParameter(this TypeSymbol type) { return type is TypeParameterSymbol { IsValueType: false, IsNotNullable: false }; } public static bool IsNonNullableValueType(this TypeSymbol typeArgument) { if (!typeArgument.IsValueType) { return false; } return !IsNullableTypeOrTypeParameter(typeArgument); } public static bool IsVoidType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_Void; } public static bool IsNullableTypeOrTypeParameter(this TypeSymbol? type) { if (type is null) { return false; } if (type.TypeKind == TypeKind.TypeParameter) { var constraintTypes = ((TypeParameterSymbol)type).ConstraintTypesNoUseSiteDiagnostics; foreach (var constraintType in constraintTypes) { if (constraintType.Type.IsNullableTypeOrTypeParameter()) { return true; } } return false; } return type.IsNullableType(); } /// <summary> /// Is this System.Nullable`1 type, or its substitution. /// /// To check whether a type is System.Nullable`1 or is a type parameter constrained to System.Nullable`1 /// use <see cref="TypeSymbolExtensions.IsNullableTypeOrTypeParameter" /> instead. /// </summary> public static bool IsNullableType(this TypeSymbol type) { return type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T; } public static bool IsValidNullableTypeArgument(this TypeSymbol type) { return type is { IsValueType: true } && !type.IsNullableType() && !type.IsPointerOrFunctionPointer() && !type.IsRestrictedType(); } public static TypeSymbol GetNullableUnderlyingType(this TypeSymbol type) { return type.GetNullableUnderlyingTypeWithAnnotations().Type; } public static TypeWithAnnotations GetNullableUnderlyingTypeWithAnnotations(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); RoslynDebug.Assert(IsNullableType(type)); RoslynDebug.Assert(type is NamedTypeSymbol); //not testing Kind because it may be an ErrorType return ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; } public static TypeSymbol StrippedType(this TypeSymbol type) { return type.IsNullableType() ? type.GetNullableUnderlyingType() : type; } public static TypeSymbol EnumUnderlyingTypeOrSelf(this TypeSymbol type) { return type.GetEnumUnderlyingType() ?? type; } public static bool IsNativeIntegerOrNullableThereof(this TypeSymbol? type) { return type?.StrippedType().IsNativeIntegerType == true; } public static bool IsObjectType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_Object; } public static bool IsStringType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_String; } public static bool IsCharType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_Char; } public static bool IsIntegralType(this TypeSymbol type) { return type.SpecialType.IsIntegralType(); } public static NamedTypeSymbol? GetEnumUnderlyingType(this TypeSymbol? type) { return (type is NamedTypeSymbol namedType) ? namedType.EnumUnderlyingType : null; } public static bool IsEnumType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Enum; } public static bool IsValidEnumType(this TypeSymbol type) { var underlyingType = type.GetEnumUnderlyingType(); // SpecialType will be None if the underlying type is invalid. return (underlyingType is object) && (underlyingType.SpecialType != SpecialType.None); } /// <summary> /// Determines if the given type is a valid attribute parameter type. /// </summary> /// <param name="type">Type to validated</param> /// <param name="compilation">compilation</param> /// <returns></returns> public static bool IsValidAttributeParameterType(this TypeSymbol type, CSharpCompilation compilation) { return GetAttributeParameterTypedConstantKind(type, compilation) != TypedConstantKind.Error; } /// <summary> /// Gets the typed constant kind for the given attribute parameter type. /// </summary> /// <param name="type">Type to validated</param> /// <param name="compilation">compilation</param> /// <returns>TypedConstantKind for the attribute parameter type.</returns> public static TypedConstantKind GetAttributeParameterTypedConstantKind(this TypeSymbol type, CSharpCompilation compilation) { // Spec (17.1.3) // The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are: // 1) One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort. // 2) The type object. // 3) The type System.Type. // 4) An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility. // 5) Single-dimensional arrays of the above types. // A constructor argument or public field which does not have one of these types, cannot be used as a positional // or named parameter in an attribute specification. TypedConstantKind kind = TypedConstantKind.Error; if ((object)type == null) { return TypedConstantKind.Error; } if (type.Kind == SymbolKind.ArrayType) { var arrayType = (ArrayTypeSymbol)type; if (!arrayType.IsSZArray) { return TypedConstantKind.Error; } kind = TypedConstantKind.Array; type = arrayType.ElementType; } // enum or enum[] if (type.IsEnumType()) { // SPEC VIOLATION: Dev11 doesn't enforce either the Enum type or its enclosing types (if any) to have public accessibility. // We will be consistent with Dev11 behavior. if (kind == TypedConstantKind.Error) { // set only if kind is not already set (i.e. its not an array of enum) kind = TypedConstantKind.Enum; } type = type.GetEnumUnderlyingType()!; } var typedConstantKind = TypedConstant.GetTypedConstantKind(type, compilation); switch (typedConstantKind) { case TypedConstantKind.Array: case TypedConstantKind.Enum: case TypedConstantKind.Error: return TypedConstantKind.Error; default: if (kind == TypedConstantKind.Array || kind == TypedConstantKind.Enum) { // Array/Enum type with valid element/underlying type return kind; } return typedConstantKind; } } public static bool IsValidExtensionParameterType(this TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Pointer: case TypeKind.Dynamic: case TypeKind.FunctionPointer: return false; default: return true; } } public static bool IsInterfaceType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)type).IsInterface; } public static bool IsClassType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Class; } public static bool IsStructType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Struct; } public static bool IsErrorType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.Kind == SymbolKind.ErrorType; } public static bool IsMethodTypeParameter(this TypeParameterSymbol p) { return p.ContainingSymbol.Kind == SymbolKind.Method; } public static bool IsDynamic(this TypeSymbol type) { return type.TypeKind == TypeKind.Dynamic; } public static bool IsTypeParameter(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.TypeParameter; } public static bool IsArray(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Array; } public static bool IsSZArray(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Array && ((ArrayTypeSymbol)type).IsSZArray; } public static bool IsFunctionPointer(this TypeSymbol type) { return type.TypeKind == TypeKind.FunctionPointer; } public static bool IsPointerOrFunctionPointer(this TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Pointer: case TypeKind.FunctionPointer: return true; default: return false; } } // If the type is a delegate type, it returns it. If the type is an // expression tree type associated with a delegate type, it returns // the delegate type. Otherwise, null. public static NamedTypeSymbol? GetDelegateType(this TypeSymbol? type) { if (type is null) return null; if (type.IsExpressionTree()) { type = ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; } return type.IsDelegateType() ? (NamedTypeSymbol)type : null; } public static TypeSymbol? GetDelegateOrFunctionPointerType(this TypeSymbol? type) { return (TypeSymbol?)GetDelegateType(type) ?? type as FunctionPointerTypeSymbol; } /// <summary> /// Returns true if the type is constructed from a generic type named "System.Linq.Expressions.Expression" /// with one type parameter. /// </summary> public static bool IsExpressionTree(this TypeSymbol type) { return type.IsGenericOrNonGenericExpressionType(out bool isGenericType) && isGenericType; } /// <summary> /// Returns true if the type is a non-generic type named "System.Linq.Expressions.Expression" /// or "System.Linq.Expressions.LambdaExpression". /// </summary> public static bool IsNonGenericExpressionType(this TypeSymbol type) { return type.IsGenericOrNonGenericExpressionType(out bool isGenericType) && !isGenericType; } /// <summary> /// Returns true if the type is constructed from a generic type named "System.Linq.Expressions.Expression" /// with one type parameter, or if the type is a non-generic type named "System.Linq.Expressions.Expression" /// or "System.Linq.Expressions.LambdaExpression". /// </summary> public static bool IsGenericOrNonGenericExpressionType(this TypeSymbol _type, out bool isGenericType) { if (_type.OriginalDefinition is NamedTypeSymbol type) { switch (type.Name) { case "Expression": if (IsNamespaceName(type.ContainingSymbol, s_expressionsNamespaceName)) { if (type.Arity == 0) { isGenericType = false; return true; } if (type.Arity == 1 && type.MangleName) { isGenericType = true; return true; } } break; case "LambdaExpression": if (IsNamespaceName(type.ContainingSymbol, s_expressionsNamespaceName) && type.Arity == 0) { isGenericType = false; return true; } break; } } isGenericType = false; return false; } /// <summary> /// return true if the type is constructed from a generic interface that /// might be implemented by an array. /// </summary> public static bool IsPossibleArrayGenericInterface(this TypeSymbol type) { if (!(type is NamedTypeSymbol t)) { return false; } t = t.OriginalDefinition; SpecialType st = t.SpecialType; if (st == SpecialType.System_Collections_Generic_IList_T || st == SpecialType.System_Collections_Generic_ICollection_T || st == SpecialType.System_Collections_Generic_IEnumerable_T || st == SpecialType.System_Collections_Generic_IReadOnlyList_T || st == SpecialType.System_Collections_Generic_IReadOnlyCollection_T) { return true; } return false; } internal static bool IsErrorTypeOrRefLikeType(this TypeSymbol type) { return type.IsErrorType() || type.IsRefLikeType; } private static readonly string[] s_expressionsNamespaceName = { "Expressions", "Linq", MetadataHelpers.SystemString, "" }; private static bool IsNamespaceName(Symbol symbol, string[] names) { if (symbol.Kind != SymbolKind.Namespace) { return false; } for (int i = 0; i < names.Length; i++) { if ((object)symbol == null || symbol.Name != names[i]) return false; symbol = symbol.ContainingSymbol; } return true; } public static bool IsDelegateType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Delegate; } public static ImmutableArray<ParameterSymbol> DelegateParameters(this TypeSymbol type) { var invokeMethod = type.DelegateInvokeMethod(); if (invokeMethod is null) { return default(ImmutableArray<ParameterSymbol>); } return invokeMethod.Parameters; } public static ImmutableArray<ParameterSymbol> DelegateOrFunctionPointerParameters(this TypeSymbol type) { Debug.Assert(type is FunctionPointerTypeSymbol || type.IsDelegateType()); if (type is FunctionPointerTypeSymbol { Signature: { Parameters: var functionPointerParameters } }) { return functionPointerParameters; } else { return type.DelegateParameters(); } } public static bool TryGetElementTypesWithAnnotationsIfTupleType(this TypeSymbol type, out ImmutableArray<TypeWithAnnotations> elementTypes) { if (type.IsTupleType) { elementTypes = ((NamedTypeSymbol)type).TupleElementTypesWithAnnotations; return true; } // source not a tuple elementTypes = default(ImmutableArray<TypeWithAnnotations>); return false; } public static MethodSymbol? DelegateInvokeMethod(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); RoslynDebug.Assert(type.IsDelegateType() || type.IsExpressionTree()); return type.GetDelegateType()!.DelegateInvokeMethod; } /// <summary> /// Return the default value constant for the given type, /// or null if the default value is not a constant. /// </summary> public static ConstantValue? GetDefaultValue(this TypeSymbol type) { // SPEC: A default-value-expression is a constant expression (§7.19) if the type // SPEC: is a reference type or a type parameter that is known to be a reference type (§10.1.5). // SPEC: In addition, a default-value-expression is a constant expression if the type is // SPEC: one of the following value types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or any enumeration type. RoslynDebug.Assert((object)type != null); if (type.IsErrorType()) { return null; } if (type.IsReferenceType) { return ConstantValue.Null; } if (type.IsValueType) { type = type.EnumUnderlyingTypeOrSelf(); switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: case SpecialType.System_Char: case SpecialType.System_Boolean: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: return ConstantValue.Default(type.SpecialType); } } return null; } public static SpecialType GetSpecialTypeSafe(this TypeSymbol? type) { return type is object ? type.SpecialType : SpecialType.None; } public static bool IsAtLeastAsVisibleAs(this TypeSymbol type, Symbol sym, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { CompoundUseSiteInfo<AssemblySymbol> localUseSiteInfo = useSiteInfo; var result = type.VisitType((type1, symbol, unused) => IsTypeLessVisibleThan(type1, symbol, ref localUseSiteInfo), sym, canDigThroughNullable: true); // System.Nullable is public useSiteInfo = localUseSiteInfo; return result is null; } private static bool IsTypeLessVisibleThan(TypeSymbol type, Symbol sym, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (type.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Enum: case TypeKind.Delegate: case TypeKind.Submission: return !IsAsRestrictive((NamedTypeSymbol)type, sym, ref useSiteInfo); default: return false; } } /// <summary> /// Visit the given type and, in the case of compound types, visit all "sub type" /// (such as A in A[], or { A&lt;T&gt;, T, U } in A&lt;T&gt;.B&lt;U&gt;) invoking 'predicate' /// with the type and 'arg' at each sub type. If the predicate returns true for any type, /// traversal stops and that type is returned from this method. Otherwise if traversal /// completes without the predicate returning true for any type, this method returns null. /// </summary> public static TypeSymbol? VisitType<T>( this TypeSymbol type, Func<TypeSymbol, T, bool, bool> predicate, T arg, bool canDigThroughNullable = false, bool visitCustomModifiers = false) { return VisitType( typeWithAnnotationsOpt: default, type: type, typeWithAnnotationsPredicate: null, typePredicate: predicate, arg, canDigThroughNullable, visitCustomModifiers: visitCustomModifiers); } /// <summary> /// Visit the given type and, in the case of compound types, visit all "sub type". /// One of the predicates will be invoked at each type. If the type is a /// TypeWithAnnotations, <paramref name="typeWithAnnotationsPredicate"/> /// will be invoked; otherwise <paramref name="typePredicate"/> will be invoked. /// If the corresponding predicate returns true for any type, /// traversal stops and that type is returned from this method. Otherwise if traversal /// completes without the predicate returning true for any type, this method returns null. /// </summary> /// <param name="useDefaultType">If true, use <see cref="TypeWithAnnotations.DefaultType"/> /// instead of <see cref="TypeWithAnnotations.Type"/> to avoid early resolution of nullable types</param> public static TypeSymbol? VisitType<T>( this TypeWithAnnotations typeWithAnnotationsOpt, TypeSymbol? type, Func<TypeWithAnnotations, T, bool, bool>? typeWithAnnotationsPredicate, Func<TypeSymbol, T, bool, bool>? typePredicate, T arg, bool canDigThroughNullable = false, bool useDefaultType = false, bool visitCustomModifiers = false) { RoslynDebug.Assert(typeWithAnnotationsOpt.HasType == (type is null)); RoslynDebug.Assert(canDigThroughNullable == false || useDefaultType == false, "digging through nullable will cause early resolution of nullable types"); RoslynDebug.Assert(canDigThroughNullable == false || visitCustomModifiers == false); RoslynDebug.Assert(visitCustomModifiers == false || typePredicate is { }); // In order to handle extremely "deep" types like "int[][][][][][][][][]...[]" // or int*****************...* we implement manual tail recursion rather than // doing the natural recursion. while (true) { TypeSymbol current = type ?? (useDefaultType ? typeWithAnnotationsOpt.DefaultType : typeWithAnnotationsOpt.Type); bool isNestedNamedType = false; // Visit containing types from outer-most to inner-most. switch (current.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Enum: case TypeKind.Delegate: { var containingType = current.ContainingType; if ((object)containingType != null) { isNestedNamedType = true; var result = VisitType(default, containingType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); if (result is object) { return result; } } } break; case TypeKind.Submission: RoslynDebug.Assert((object)current.ContainingType == null); break; } if (typeWithAnnotationsOpt.HasType && typeWithAnnotationsPredicate != null) { if (typeWithAnnotationsPredicate(typeWithAnnotationsOpt, arg, isNestedNamedType)) { return current; } } else if (typePredicate != null) { if (typePredicate(current, arg, isNestedNamedType)) { return current; } } if (visitCustomModifiers && typeWithAnnotationsOpt.HasType) { foreach (var customModifier in typeWithAnnotationsOpt.CustomModifiers) { var result = VisitType( typeWithAnnotationsOpt: default, type: ((CSharpCustomModifier)customModifier).ModifierSymbol, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); if (result is object) { return result; } } } TypeWithAnnotations next; switch (current.TypeKind) { case TypeKind.Dynamic: case TypeKind.TypeParameter: case TypeKind.Submission: case TypeKind.Enum: return null; case TypeKind.Error: case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Delegate: if (current.IsAnonymousType) { var anonymous = (AnonymousTypeManager.AnonymousTypeOrDelegatePublicSymbol)current; var fields = anonymous.TypeDescriptor.Fields; if (fields.IsEmpty) { return null; } int i; for (i = 0; i < fields.Length - 1; i++) { // Let's try to avoid early resolution of nullable types (TypeWithAnnotations nextTypeWithAnnotations, TypeSymbol? nextType) = getNextIterationElements(fields[i].TypeWithAnnotations, canDigThroughNullable); var result = VisitType( typeWithAnnotationsOpt: nextTypeWithAnnotations, type: nextType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); if (result is object) { return result; } } next = fields[i].TypeWithAnnotations; } else { var typeArguments = ((NamedTypeSymbol)current).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; if (typeArguments.IsEmpty) { return null; } int i; for (i = 0; i < typeArguments.Length - 1; i++) { // Let's try to avoid early resolution of nullable types (TypeWithAnnotations nextTypeWithAnnotations, TypeSymbol? nextType) = getNextIterationElements(typeArguments[i], canDigThroughNullable); var result = VisitType( typeWithAnnotationsOpt: nextTypeWithAnnotations, type: nextType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); if (result is object) { return result; } } next = typeArguments[i]; } break; case TypeKind.Array: next = ((ArrayTypeSymbol)current).ElementTypeWithAnnotations; break; case TypeKind.Pointer: next = ((PointerTypeSymbol)current).PointedAtTypeWithAnnotations; break; case TypeKind.FunctionPointer: { var result = visitFunctionPointerType((FunctionPointerTypeSymbol)current, typeWithAnnotationsPredicate, typePredicate, arg, useDefaultType, canDigThroughNullable, visitCustomModifiers, out next); if (result is object) { return result; } break; } default: throw ExceptionUtilities.UnexpectedValue(current.TypeKind); } // Let's try to avoid early resolution of nullable types typeWithAnnotationsOpt = canDigThroughNullable ? default : next; type = canDigThroughNullable ? next.NullableUnderlyingTypeOrSelf : null; } static (TypeWithAnnotations, TypeSymbol?) getNextIterationElements(TypeWithAnnotations type, bool canDigThroughNullable) => canDigThroughNullable ? (default(TypeWithAnnotations), type.NullableUnderlyingTypeOrSelf) : (type, null); static TypeSymbol? visitFunctionPointerType(FunctionPointerTypeSymbol type, Func<TypeWithAnnotations, T, bool, bool>? typeWithAnnotationsPredicate, Func<TypeSymbol, T, bool, bool>? typePredicate, T arg, bool useDefaultType, bool canDigThroughNullable, bool visitCustomModifiers, out TypeWithAnnotations next) { MethodSymbol currentPointer = type.Signature; if (currentPointer.ParameterCount == 0) { next = currentPointer.ReturnTypeWithAnnotations; return null; } var result = VisitType( typeWithAnnotationsOpt: canDigThroughNullable ? default : currentPointer.ReturnTypeWithAnnotations, type: canDigThroughNullable ? currentPointer.ReturnTypeWithAnnotations.NullableUnderlyingTypeOrSelf : null, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); if (result is object) { next = default; return result; } int i; for (i = 0; i < currentPointer.ParameterCount - 1; i++) { (TypeWithAnnotations nextTypeWithAnnotations, TypeSymbol? nextType) = getNextIterationElements(currentPointer.Parameters[i].TypeWithAnnotations, canDigThroughNullable); result = VisitType( typeWithAnnotationsOpt: nextTypeWithAnnotations, type: nextType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); if (result is object) { next = default; return result; } } next = currentPointer.Parameters[i].TypeWithAnnotations; return null; } } internal static bool IsAsRestrictive(this Symbol s1, Symbol sym2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Accessibility acc1 = s1.DeclaredAccessibility; if (acc1 == Accessibility.Public) { return true; } for (Symbol s2 = sym2; s2.Kind != SymbolKind.Namespace; s2 = s2.ContainingSymbol) { Accessibility acc2 = s2.DeclaredAccessibility; switch (acc1) { case Accessibility.Internal: { // If s2 is private or internal, and within the same assembly as s1, // then this is at least as restrictive as s1's internal. if ((acc2 == Accessibility.Private || acc2 == Accessibility.Internal || acc2 == Accessibility.ProtectedAndInternal) && s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { return true; } break; } case Accessibility.ProtectedAndInternal: // Since s1 is private protected, s2 must pass the test for being both more restrictive than internal and more restrictive than protected. // We first do the "internal" test (copied from above), then if it passes we continue with the "protected" test. if ((acc2 == Accessibility.Private || acc2 == Accessibility.Internal || acc2 == Accessibility.ProtectedAndInternal) && s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { // passed the internal test; now do the test for the protected case goto case Accessibility.Protected; } break; case Accessibility.Protected: { var parent1 = s1.ContainingType; if ((object)parent1 == null) { // not helpful } else if (acc2 == Accessibility.Private) { // if s2 is private and within s1's parent or within a subclass of s1's parent, // then this is at least as restrictive as s1's protected. for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType) { if (parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo)) { return true; } } } else if (acc2 == Accessibility.Protected || acc2 == Accessibility.ProtectedAndInternal) { // if s2 is protected, and it's parent is a subclass (or the same as) s1's parent // then this is at least as restrictive as s1's protected var parent2 = s2.ContainingType; if ((object)parent2 != null && parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo)) { return true; } } break; } case Accessibility.ProtectedOrInternal: { var parent1 = s1.ContainingType; if ((object)parent1 == null) { break; } switch (acc2) { case Accessibility.Private: // if s2 is private and within a subclass of s1's parent, // or within the same assembly as s1 // then this is at least as restrictive as s1's internal protected. if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { return true; } for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType) { if (parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo)) { return true; } } break; case Accessibility.Internal: // If s2 is in the same assembly as s1, then this is more restrictive // than s1's internal protected. if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { return true; } break; case Accessibility.Protected: // if s2 is protected, and it's parent is a subclass (or the same as) s1's parent // then this is at least as restrictive as s1's internal protected if (parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo)) { return true; } break; case Accessibility.ProtectedAndInternal: // if s2 is private protected, and it's parent is a subclass (or the same as) s1's parent // or its in the same assembly as s1, then this is at least as restrictive as s1's protected if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly) || parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo)) { return true; } break; case Accessibility.ProtectedOrInternal: // if s2 is internal protected, and it's parent is a subclass (or the same as) s1's parent // and its in the same assembly as s1, then this is at least as restrictive as s1's protected if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly) && parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo)) { return true; } break; } break; } case Accessibility.Private: if (acc2 == Accessibility.Private) { // if s2 is private, and it is within s1's parent, then this is at // least as restrictive as s1's private. NamedTypeSymbol parent1 = s1.ContainingType; if ((object)parent1 == null) { break; } var parent1OriginalDefinition = parent1.OriginalDefinition; for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType) { if (ReferenceEquals(parent2.OriginalDefinition, parent1OriginalDefinition) || parent1OriginalDefinition.TypeKind == TypeKind.Submission && parent2.TypeKind == TypeKind.Submission) { return true; } } } break; default: throw ExceptionUtilities.UnexpectedValue(acc1); } } return false; } public static bool IsUnboundGenericType(this TypeSymbol type) { return type is NamedTypeSymbol { IsUnboundGenericType: true }; } public static bool IsTopLevelType(this NamedTypeSymbol type) { return (object)type.ContainingType == null; } /// <summary> /// (null TypeParameterSymbol "parameter"): Checks if the given type is a type parameter /// or its referent type is a type parameter (array/pointer) or contains a type parameter (aggregate type) /// (non-null TypeParameterSymbol "parameter"): above + also checks if the type parameter /// is the same as "parameter" /// </summary> public static bool ContainsTypeParameter(this TypeSymbol type, TypeParameterSymbol? parameter = null) { var result = type.VisitType(s_containsTypeParameterPredicate, parameter); return result is object; } private static readonly Func<TypeSymbol, TypeParameterSymbol?, bool, bool> s_containsTypeParameterPredicate = (type, parameter, unused) => type.TypeKind == TypeKind.TypeParameter && (parameter is null || TypeSymbol.Equals(type, parameter, TypeCompareKind.ConsiderEverything2)); public static bool ContainsTypeParameter(this TypeSymbol type, MethodSymbol parameterContainer) { RoslynDebug.Assert((object)parameterContainer != null); var result = type.VisitType(s_isTypeParameterWithSpecificContainerPredicate, parameterContainer); return result is object; } private static readonly Func<TypeSymbol, Symbol, bool, bool> s_isTypeParameterWithSpecificContainerPredicate = (type, parameterContainer, unused) => type.TypeKind == TypeKind.TypeParameter && (object)type.ContainingSymbol == (object)parameterContainer; public static bool ContainsTypeParameters(this TypeSymbol type, HashSet<TypeParameterSymbol> parameters) { var result = type.VisitType(s_containsTypeParametersPredicate, parameters); return result is object; } private static readonly Func<TypeSymbol, HashSet<TypeParameterSymbol>, bool, bool> s_containsTypeParametersPredicate = (type, parameters, unused) => type.TypeKind == TypeKind.TypeParameter && parameters.Contains((TypeParameterSymbol)type); public static bool ContainsMethodTypeParameter(this TypeSymbol type) { var result = type.VisitType(s_containsMethodTypeParameterPredicate, null); return result is object; } private static readonly Func<TypeSymbol, object?, bool, bool> s_containsMethodTypeParameterPredicate = (type, _, _) => type.TypeKind == TypeKind.TypeParameter && type.ContainingSymbol is MethodSymbol; /// <summary> /// Return true if the type contains any dynamic type reference. /// </summary> public static bool ContainsDynamic(this TypeSymbol type) { var result = type.VisitType(s_containsDynamicPredicate, null, canDigThroughNullable: true); return result is object; } private static readonly Func<TypeSymbol, object?, bool, bool> s_containsDynamicPredicate = (type, unused1, unused2) => type.TypeKind == TypeKind.Dynamic; internal static bool ContainsNativeIntegerWrapperType(this TypeSymbol type) { var result = type.VisitType((type, unused1, unused2) => type.IsNativeIntegerWrapperType, (object?)null, canDigThroughNullable: true); return result is object; } internal static bool ContainsNativeIntegerWrapperType(this TypeWithAnnotations type) { return type.Type?.ContainsNativeIntegerWrapperType() == true; } internal static bool ContainsErrorType(this TypeSymbol type) { var result = type.VisitType((type, unused1, unused2) => type.IsErrorType(), (object?)null, canDigThroughNullable: true); return result is object; } /// <summary> /// Return true if the type contains any tuples. /// </summary> internal static bool ContainsTuple(this TypeSymbol type) => type.VisitType((TypeSymbol t, object? _1, bool _2) => t.IsTupleType, null) is object; /// <summary> /// Return true if the type contains any tuples with element names. /// </summary> internal static bool ContainsTupleNames(this TypeSymbol type) => type.VisitType((TypeSymbol t, object? _1, bool _2) => !t.TupleElementNames.IsDefault, null) is object; /// <summary> /// Return true if the type contains any function pointer types. /// </summary> internal static bool ContainsFunctionPointer(this TypeSymbol type) => type.VisitType((TypeSymbol t, object? _, bool _) => t.IsFunctionPointer(), null) is object; /// <summary> /// Guess the non-error type that the given type was intended to represent. /// If the type itself is not an error type, then it will be returned. /// Otherwise, the underlying type (if any) of the error type will be /// returned. /// </summary> /// <remarks> /// Any non-null type symbol returned is guaranteed not to be an error type. /// /// It is possible to pass in a constructed type and received back an /// unconstructed type. This can occur when the type passed in was /// constructed from an error type - the underlying definition will be /// available, but there won't be a good way to "re-substitute" back up /// to the level of the specified type. /// </remarks> internal static TypeSymbol? GetNonErrorGuess(this TypeSymbol type) { var result = ExtendedErrorTypeSymbol.ExtractNonErrorType(type); RoslynDebug.Assert((object?)result == null || !result.IsErrorType()); return result; } /// <summary> /// Guess the non-error type kind that the given type was intended to represent, /// if possible. If not, return TypeKind.Error. /// </summary> internal static TypeKind GetNonErrorTypeKindGuess(this TypeSymbol type) { return ExtendedErrorTypeSymbol.ExtractNonErrorTypeKind(type); } /// <summary> /// Returns true if the type was a valid switch expression type in C# 6. We use this test to determine /// whether or not we should attempt a user-defined conversion from the type to a C# 6 switch governing /// type, which we support for compatibility with C# 6 and earlier. /// </summary> internal static bool IsValidV6SwitchGoverningType(this TypeSymbol type, bool isTargetTypeOfUserDefinedOp = false) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types RoslynDebug.Assert((object)type != null); if (type.IsNullableType()) { type = type.GetNullableUnderlyingType(); } // User-defined implicit conversion with target type as Enum type is not valid. if (!isTargetTypeOfUserDefinedOp) { type = type.EnumUnderlyingTypeOrSelf(); } switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Char: case SpecialType.System_String: return true; case SpecialType.System_Boolean: // User-defined implicit conversion with target type as bool type is not valid. return !isTargetTypeOfUserDefinedOp; } return false; } internal static bool IsSpanChar(this TypeSymbol type) { return type is NamedTypeSymbol { ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, MetadataName: "Span`1", TypeArgumentsWithAnnotationsNoUseSiteDiagnostics: { Length: 1 } arguments, } && arguments[0].SpecialType == SpecialType.System_Char; } internal static bool IsReadOnlySpanChar(this TypeSymbol type) { return type is NamedTypeSymbol { ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, MetadataName: "ReadOnlySpan`1", TypeArgumentsWithAnnotationsNoUseSiteDiagnostics: { Length: 1 } arguments, } && arguments[0].SpecialType == SpecialType.System_Char; } internal static bool IsSpanOrReadOnlySpanChar(this TypeSymbol type) { return type is NamedTypeSymbol { ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, MetadataName: "ReadOnlySpan`1" or "Span`1", TypeArgumentsWithAnnotationsNoUseSiteDiagnostics: { Length: 1 } arguments, } && arguments[0].SpecialType == SpecialType.System_Char; } #pragma warning disable CA1200 // Avoid using cref tags with a prefix /// <summary> /// Returns true if the type is one of the restricted types, namely: <see cref="T:System.TypedReference"/>, /// <see cref="T:System.ArgIterator"/>, or <see cref="T:System.RuntimeArgumentHandle"/>. /// or a ref-like type. /// </summary> #pragma warning restore CA1200 // Avoid using cref tags with a prefix internal static bool IsRestrictedType(this TypeSymbol type, bool ignoreSpanLikeTypes = false) { // See Dev10 C# compiler, "type.cpp", bool Type::isSpecialByRefType() const RoslynDebug.Assert((object)type != null); switch (type.SpecialType) { case SpecialType.System_TypedReference: case SpecialType.System_ArgIterator: case SpecialType.System_RuntimeArgumentHandle: return true; } return ignoreSpanLikeTypes ? false : type.IsRefLikeType; } public static bool IsIntrinsicType(this TypeSymbol type) { switch (type.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_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: case SpecialType.System_Single: case SpecialType.System_Double: // NOTE: VB treats System.DateTime as an intrinsic, while C# does not. //case SpecialType.System_DateTime: case SpecialType.System_Decimal: return true; default: return false; } } public static bool IsPartial(this TypeSymbol type) { return type is SourceNamedTypeSymbol { IsPartial: true }; } public static bool IsFileTypeOrUsesFileTypes(this TypeSymbol type) { var foundType = type.VisitType(predicate: (type, _, _) => type is SourceMemberContainerTypeSymbol { IsFile: true }, arg: (object?)null); return foundType is not null; } internal static string? AssociatedFileIdentifier(this NamedTypeSymbol type) { if (type.AssociatedSyntaxTree is not SyntaxTree tree) { return null; } var ordinal = type.DeclaringCompilation.GetSyntaxTreeOrdinal(tree); return GeneratedNames.MakeFileIdentifier(tree.FilePath, ordinal); } public static bool IsPointerType(this TypeSymbol type) { return type is PointerTypeSymbol; } internal static int FixedBufferElementSizeInBytes(this TypeSymbol type) { return type.SpecialType.FixedBufferElementSizeInBytes(); } // check that its type is allowed for Volatile internal static bool IsValidVolatileFieldType(this TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Struct: return type.SpecialType.IsValidVolatileFieldType(); case TypeKind.Array: case TypeKind.Class: case TypeKind.Delegate: case TypeKind.Dynamic: case TypeKind.Error: case TypeKind.Interface: case TypeKind.Pointer: case TypeKind.FunctionPointer: return true; case TypeKind.Enum: return ((NamedTypeSymbol)type).EnumUnderlyingType.SpecialType.IsValidVolatileFieldType(); case TypeKind.TypeParameter: return type.IsReferenceType; case TypeKind.Submission: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } return false; } /// <summary> /// Add this instance to the set of checked types. Returns true /// if this was added, false if the type was already in the set. /// </summary> public static bool MarkCheckedIfNecessary(this TypeSymbol type, ref HashSet<TypeSymbol> checkedTypes) { if (checkedTypes == null) { checkedTypes = new HashSet<TypeSymbol>(); } return checkedTypes.Add(type); } internal static bool IsUnsafe(this TypeSymbol type) { while (true) { switch (type.TypeKind) { case TypeKind.Pointer: case TypeKind.FunctionPointer: return true; case TypeKind.Array: type = ((ArrayTypeSymbol)type).ElementType; break; default: // NOTE: we could consider a generic type with unsafe type arguments to be unsafe, // but that's already an error, so there's no reason to report it. Also, this // matches Type::isUnsafe in Dev10. return false; } } } internal static bool IsVoidPointer(this TypeSymbol type) { return type is PointerTypeSymbol p && p.PointedAtType.IsVoidType(); } /// <summary> /// These special types are structs that contain fields of the same type /// (e.g. <see cref="System.Int32"/> contains an instance field of type <see cref="System.Int32"/>). /// </summary> internal static bool IsPrimitiveRecursiveStruct(this TypeSymbol t) { return t.SpecialType.IsPrimitiveRecursiveStruct(); } /// <summary> /// Compute a hash code for the constructed type. The return value will be /// non-zero so callers can used zero to represent an uninitialized value. /// </summary> internal static int ComputeHashCode(this NamedTypeSymbol type) { RoslynDebug.Assert(!type.Equals(type.OriginalDefinition, TypeCompareKind.AllIgnoreOptions) || wasConstructedForAnnotations(type)); if (wasConstructedForAnnotations(type)) { // A type that uses its own type parameters as type arguments was constructed only for the purpose of adding annotations. // In that case we'll use the hash from the definition. return type.OriginalDefinition.GetHashCode(); } int code = type.OriginalDefinition.GetHashCode(); code = Hash.Combine(type.ContainingType, code); // Unconstructed type may contain alpha-renamed type parameters while // may still be considered equal, we do not want to give different hashcode to such types. // // Example: // Having original type A<U>.B<V> we create two _unconstructed_ types // A<int>.B<V'> // A<int>.B<V"> // Note that V' and V" are type parameters substituted via alpha-renaming of original V // These are different objects, but represent the same "type parameter at index 1" // // In short - we are not interested in the type parameters of unconstructed types. if ((object)type.ConstructedFrom != (object)type) { foreach (var arg in type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { code = Hash.Combine(arg.Type, code); } } // 0 may be used by the caller to indicate the hashcode is not // initialized. If we computed 0 for the hashcode, tweak it. if (code == 0) { code++; } return code; static bool wasConstructedForAnnotations(NamedTypeSymbol type) { do { var typeArguments = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var typeParameters = type.OriginalDefinition.TypeParameters; for (int i = 0; i < typeArguments.Length; i++) { if (!typeParameters[i].Equals( typeArguments[i].Type.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { return false; } } type = type.ContainingType; } while (type is object && !type.IsDefinition); return true; } } /// <summary> /// If we are in a COM PIA with embedInteropTypes enabled we should turn properties and methods /// that have the type and return type of object, respectively, into type dynamic. If the requisite conditions /// are fulfilled, this method returns a dynamic type. If not, it returns the original type. /// </summary> /// <param name="type">A property type or method return type to be checked for dynamification.</param> /// <param name="containingType">Containing type.</param> /// <returns></returns> public static TypeSymbol AsDynamicIfNoPia(this TypeSymbol type, NamedTypeSymbol containingType) { return type.TryAsDynamicIfNoPia(containingType, out TypeSymbol? result) ? result : type; } public static bool TryAsDynamicIfNoPia(this TypeSymbol type, NamedTypeSymbol containingType, [NotNullWhen(true)] out TypeSymbol? result) { if (type.SpecialType == SpecialType.System_Object) { AssemblySymbol assembly = containingType.ContainingAssembly; if ((object)assembly != null && assembly.IsLinked && containingType.IsComImport) { result = DynamicTypeSymbol.Instance; return true; } } result = null; return false; } /// <summary> /// Type variables are never considered reference types by the verifier. /// </summary> internal static bool IsVerifierReference(this TypeSymbol type) { return type.IsReferenceType && type.TypeKind != TypeKind.TypeParameter; } /// <summary> /// Type variables are never considered value types by the verifier. /// </summary> internal static bool IsVerifierValue(this TypeSymbol type) { return type.IsValueType && type.TypeKind != TypeKind.TypeParameter; } /// <summary> /// Return all of the type parameters in this type and enclosing types, /// from outer-most to inner-most type. /// </summary> internal static ImmutableArray<TypeParameterSymbol> GetAllTypeParameters(this NamedTypeSymbol type) { // Avoid allocating a builder in the common case. if ((object)type.ContainingType == null) { return type.TypeParameters; } var builder = ArrayBuilder<TypeParameterSymbol>.GetInstance(); type.GetAllTypeParameters(builder); return builder.ToImmutableAndFree(); } /// <summary> /// Return all of the type parameters in this type and enclosing types, /// from outer-most to inner-most type. /// </summary> internal static void GetAllTypeParameters(this NamedTypeSymbol type, ArrayBuilder<TypeParameterSymbol> result) { var containingType = type.ContainingType; if ((object)containingType != null) { containingType.GetAllTypeParameters(result); } result.AddRange(type.TypeParameters); } /// <summary> /// Return the nearest type parameter with the given name in /// this type or any enclosing type. /// </summary> internal static TypeParameterSymbol? FindEnclosingTypeParameter(this NamedTypeSymbol type, string name) { var allTypeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); type.GetAllTypeParameters(allTypeParameters); TypeParameterSymbol? result = null; foreach (TypeParameterSymbol tpEnclosing in allTypeParameters) { if (name == tpEnclosing.Name) { result = tpEnclosing; break; } } allTypeParameters.Free(); return result; } /// <summary> /// Return the nearest type parameter with the given name in /// this symbol or any enclosing symbol. /// </summary> internal static TypeParameterSymbol? FindEnclosingTypeParameter(this Symbol methodOrType, string name) { while (methodOrType != null) { switch (methodOrType.Kind) { case SymbolKind.Method: case SymbolKind.NamedType: case SymbolKind.ErrorType: case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: break; default: return null; } foreach (var typeParameter in methodOrType.GetMemberTypeParameters()) { if (typeParameter.Name == name) { return typeParameter; } } methodOrType = methodOrType.ContainingSymbol; } return null; } /// <summary> /// Return true if the fully qualified name of the type's containing symbol /// matches the given name. This method avoids string concatenations /// in the common case where the type is a top-level type. /// </summary> internal static bool HasNameQualifier(this NamedTypeSymbol type, string qualifiedName) { const StringComparison comparison = StringComparison.Ordinal; var container = type.ContainingSymbol; if (container.Kind != SymbolKind.Namespace) { // Nested type. For simplicity, compare qualified name to SymbolDisplay result. return string.Equals(container.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), qualifiedName, comparison); } var @namespace = (NamespaceSymbol)container; if (@namespace.IsGlobalNamespace) { return qualifiedName.Length == 0; } return HasNamespaceName(@namespace, qualifiedName, comparison, length: qualifiedName.Length); } private static bool HasNamespaceName(NamespaceSymbol @namespace, string namespaceName, StringComparison comparison, int length) { if (length == 0) { return false; } var container = @namespace.ContainingNamespace; int separator = namespaceName.LastIndexOf('.', length - 1, length); int offset = 0; if (separator >= 0) { if (container.IsGlobalNamespace) { return false; } if (!HasNamespaceName(container, namespaceName, comparison, length: separator)) { return false; } int n = separator + 1; offset = n; length -= n; } else if (!container.IsGlobalNamespace) { return false; } var name = @namespace.Name; return (name.Length == length) && (string.Compare(name, 0, namespaceName, offset, length, comparison) == 0); } internal static bool IsNonGenericTaskType(this TypeSymbol type, CSharpCompilation compilation) { var namedType = type as NamedTypeSymbol; if (namedType is null || namedType.Arity != 0) { return false; } if ((object)namedType == compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task)) { return true; } if (namedType.IsVoidType()) { return false; } return namedType.IsCustomTaskType(builderArgument: out _); } internal static bool IsGenericTaskType(this TypeSymbol type, CSharpCompilation compilation) { if (!(type is NamedTypeSymbol { Arity: 1 } namedType)) { return false; } if ((object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T)) { return true; } return namedType.IsCustomTaskType(builderArgument: out _); } internal static bool IsIAsyncEnumerableType(this TypeSymbol type, CSharpCompilation compilation) { if (!(type is NamedTypeSymbol { Arity: 1 } namedType)) { return false; } return (object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T); } internal static bool IsIAsyncEnumeratorType(this TypeSymbol type, CSharpCompilation compilation) { if (!(type is NamedTypeSymbol { Arity: 1 } namedType)) { return false; } return (object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T); } /// <summary> /// Returns true if the type is generic or non-generic custom task-like type due to the /// [AsyncMethodBuilder(typeof(B))] attribute. It returns the "B". /// </summary> /// <remarks> /// For the Task types themselves, this method might return true or false depending on mscorlib. /// The definition of "custom task-like type" is one that has an [AsyncMethodBuilder(typeof(B))] attribute, /// no more, no less. Validation of builder type B is left for elsewhere. This method returns B /// without validation of any kind. /// </remarks> internal static bool IsCustomTaskType(this NamedTypeSymbol type, [NotNullWhen(true)] out object? builderArgument) { RoslynDebug.Assert((object)type != null); var arity = type.Arity; if (arity < 2) { return type.HasAsyncMethodBuilderAttribute(out builderArgument); } builderArgument = null; return false; } /// <summary> /// Replace Task-like types with Task types. /// </summary> internal static TypeSymbol NormalizeTaskTypes(this TypeSymbol type, CSharpCompilation compilation) { NormalizeTaskTypesInType(compilation, ref type); return type; } /// <summary> /// Replace Task-like types with Task types. Returns true if there were changes. /// </summary> private static bool NormalizeTaskTypesInType(CSharpCompilation compilation, ref TypeSymbol type) { switch (type.Kind) { case SymbolKind.NamedType: case SymbolKind.ErrorType: { var namedType = (NamedTypeSymbol)type; var changed = NormalizeTaskTypesInNamedType(compilation, ref namedType); type = namedType; return changed; } case SymbolKind.ArrayType: { var arrayType = (ArrayTypeSymbol)type; var changed = NormalizeTaskTypesInArray(compilation, ref arrayType); type = arrayType; return changed; } case SymbolKind.PointerType: { var pointerType = (PointerTypeSymbol)type; var changed = NormalizeTaskTypesInPointer(compilation, ref pointerType); type = pointerType; return changed; } case SymbolKind.FunctionPointerType: { var functionPointerType = (FunctionPointerTypeSymbol)type; var changed = NormalizeTaskTypesInFunctionPointer(compilation, ref functionPointerType); type = functionPointerType; return changed; } } return false; } private static bool NormalizeTaskTypesInType(CSharpCompilation compilation, ref TypeWithAnnotations typeWithAnnotations) { var type = typeWithAnnotations.Type; if (NormalizeTaskTypesInType(compilation, ref type)) { typeWithAnnotations = TypeWithAnnotations.Create(type, customModifiers: typeWithAnnotations.CustomModifiers); return true; } return false; } private static bool NormalizeTaskTypesInNamedType(CSharpCompilation compilation, ref NamedTypeSymbol type) { bool hasChanged = false; if (!type.IsDefinition) { RoslynDebug.Assert(type.IsGenericType); var typeArgumentsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; type.GetAllTypeArguments(typeArgumentsBuilder, ref discardedUseSiteInfo); for (int i = 0; i < typeArgumentsBuilder.Count; i++) { var typeWithModifier = typeArgumentsBuilder[i]; var typeArgNormalized = typeWithModifier.Type; if (NormalizeTaskTypesInType(compilation, ref typeArgNormalized)) { hasChanged = true; // Preserve custom modifiers but without normalizing those types. typeArgumentsBuilder[i] = TypeWithAnnotations.Create(typeArgNormalized, customModifiers: typeWithModifier.CustomModifiers); } } if (hasChanged) { var originalType = type; var originalDefinition = originalType.OriginalDefinition; var typeParameters = originalDefinition.GetAllTypeParameters(); var typeMap = new TypeMap(typeParameters, typeArgumentsBuilder.ToImmutable(), allowAlpha: true); type = typeMap.SubstituteNamedType(originalDefinition).WithTupleDataFrom(originalType); } typeArgumentsBuilder.Free(); } if (type.OriginalDefinition.IsCustomTaskType(builderArgument: out _)) { int arity = type.Arity; RoslynDebug.Assert(arity < 2); var taskType = compilation.GetWellKnownType( arity == 0 ? WellKnownType.System_Threading_Tasks_Task : WellKnownType.System_Threading_Tasks_Task_T); if (taskType.TypeKind == TypeKind.Error) { // Skip if Task types are not available. return false; } type = arity == 0 ? taskType : taskType.Construct( ImmutableArray.Create(type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]), unbound: false); hasChanged = true; } return hasChanged; } private static bool NormalizeTaskTypesInArray(CSharpCompilation compilation, ref ArrayTypeSymbol arrayType) { var elementType = arrayType.ElementTypeWithAnnotations; if (!NormalizeTaskTypesInType(compilation, ref elementType)) { return false; } arrayType = arrayType.WithElementType(elementType); return true; } private static bool NormalizeTaskTypesInPointer(CSharpCompilation compilation, ref PointerTypeSymbol pointerType) { var pointedAtType = pointerType.PointedAtTypeWithAnnotations; if (!NormalizeTaskTypesInType(compilation, ref pointedAtType)) { return false; } // Preserve custom modifiers but without normalizing those types. pointerType = new PointerTypeSymbol(pointedAtType); return true; } private static bool NormalizeTaskTypesInFunctionPointer(CSharpCompilation compilation, ref FunctionPointerTypeSymbol funcPtrType) { var returnType = funcPtrType.Signature.ReturnTypeWithAnnotations; var madeChanges = NormalizeTaskTypesInType(compilation, ref returnType); var paramTypes = ImmutableArray<TypeWithAnnotations>.Empty; if (funcPtrType.Signature.ParameterCount > 0) { var paramsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(funcPtrType.Signature.ParameterCount); bool madeParamChanges = false; foreach (var param in funcPtrType.Signature.Parameters) { var paramType = param.TypeWithAnnotations; madeParamChanges |= NormalizeTaskTypesInType(compilation, ref paramType); paramsBuilder.Add(paramType); } if (madeParamChanges) { madeChanges = true; paramTypes = paramsBuilder.ToImmutableAndFree(); } else { paramTypes = funcPtrType.Signature.ParameterTypesWithAnnotations; paramsBuilder.Free(); } } if (madeChanges) { funcPtrType = funcPtrType.SubstituteTypeSymbol(returnType, paramTypes, refCustomModifiers: default, paramRefCustomModifiers: default); return true; } else { return false; } } internal static Cci.TypeReferenceWithAttributes GetTypeRefWithAttributes( this TypeWithAnnotations type, Emit.PEModuleBuilder moduleBuilder, Symbol declaringSymbol, Cci.ITypeReference typeRef) { var builder = ArrayBuilder<Cci.ICustomAttribute>.GetInstance(); var compilation = declaringSymbol.DeclaringCompilation; if (compilation != null) { if (type.Type.ContainsTupleNames()) { addIfNotNull(builder, compilation.SynthesizeTupleNamesAttribute(type.Type)); } if (compilation.ShouldEmitNativeIntegerAttributes(type.Type)) { addIfNotNull(builder, moduleBuilder.SynthesizeNativeIntegerAttribute(declaringSymbol, type.Type)); } if (compilation.ShouldEmitNullableAttributes(declaringSymbol)) { addIfNotNull(builder, moduleBuilder.SynthesizeNullableAttributeIfNecessary(declaringSymbol, declaringSymbol.GetNullableContextValue(), type)); } static void addIfNotNull(ArrayBuilder<Cci.ICustomAttribute> builder, SynthesizedAttributeData? attr) { if (attr != null) { builder.Add(attr); } } } return new Cci.TypeReferenceWithAttributes(typeRef, builder.ToImmutableAndFree()); } internal static bool IsWellKnownTypeInAttribute(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownInteropServicesTopLevelType("InAttribute"); internal static bool IsWellKnownTypeUnmanagedType(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownInteropServicesTopLevelType("UnmanagedType"); internal static bool IsWellKnownTypeIsExternalInit(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownCompilerServicesTopLevelType("IsExternalInit"); internal static bool IsWellKnownTypeOutAttribute(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownInteropServicesTopLevelType("OutAttribute"); private static bool IsWellKnownInteropServicesTopLevelType(this TypeSymbol typeSymbol, string name) { if (typeSymbol.Name != name || typeSymbol.ContainingType is object) { return false; } return IsContainedInNamespace(typeSymbol, "System", "Runtime", "InteropServices"); } private static bool IsWellKnownCompilerServicesTopLevelType(this TypeSymbol typeSymbol, string name) { if (typeSymbol.Name != name) { return false; } return IsCompilerServicesTopLevelType(typeSymbol); } internal static bool IsCompilerServicesTopLevelType(this TypeSymbol typeSymbol) => typeSymbol.ContainingType is null && IsContainedInNamespace(typeSymbol, "System", "Runtime", "CompilerServices"); internal static bool IsWellKnownSetsRequiredMembersAttribute(this TypeSymbol type) => type.Name == "SetsRequiredMembersAttribute" && type.IsWellKnownDiagnosticsCodeAnalysisTopLevelType(); private static bool IsWellKnownDiagnosticsCodeAnalysisTopLevelType(this TypeSymbol typeSymbol) => typeSymbol.ContainingType is null && IsContainedInNamespace(typeSymbol, "System", "Diagnostics", "CodeAnalysis"); private static bool IsContainedInNamespace(this TypeSymbol typeSymbol, string outerNS, string midNS, string innerNS) { var innerNamespace = typeSymbol.ContainingNamespace; if (innerNamespace?.Name != innerNS) { return false; } var midNamespace = innerNamespace.ContainingNamespace; if (midNamespace?.Name != midNS) { return false; } var outerNamespace = midNamespace.ContainingNamespace; if (outerNamespace?.Name != outerNS) { return false; } var globalNamespace = outerNamespace.ContainingNamespace; return globalNamespace != null && globalNamespace.IsGlobalNamespace; } internal static int TypeToIndex(this TypeSymbol type) { switch (type.GetSpecialTypeSafe()) { case SpecialType.System_Object: return 0; case SpecialType.System_String: return 1; case SpecialType.System_Boolean: return 2; case SpecialType.System_Char: return 3; case SpecialType.System_SByte: return 4; case SpecialType.System_Int16: return 5; case SpecialType.System_Int32: return 6; case SpecialType.System_Int64: return 7; case SpecialType.System_Byte: return 8; case SpecialType.System_UInt16: return 9; case SpecialType.System_UInt32: return 10; case SpecialType.System_UInt64: return 11; case SpecialType.System_IntPtr when type.IsNativeIntegerType: return 12; case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return 13; case SpecialType.System_Single: return 14; case SpecialType.System_Double: return 15; case SpecialType.System_Decimal: return 16; case SpecialType.None: if ((object)type != null && type.IsNullableType()) { TypeSymbol underlyingType = type.GetNullableUnderlyingType(); switch (underlyingType.GetSpecialTypeSafe()) { case SpecialType.System_Boolean: return 17; case SpecialType.System_Char: return 18; case SpecialType.System_SByte: return 19; case SpecialType.System_Int16: return 20; case SpecialType.System_Int32: return 21; case SpecialType.System_Int64: return 22; case SpecialType.System_Byte: return 23; case SpecialType.System_UInt16: return 24; case SpecialType.System_UInt32: return 25; case SpecialType.System_UInt64: return 26; case SpecialType.System_IntPtr when underlyingType.IsNativeIntegerType: return 27; case SpecialType.System_UIntPtr when underlyingType.IsNativeIntegerType: return 28; case SpecialType.System_Single: return 29; case SpecialType.System_Double: return 30; case SpecialType.System_Decimal: return 31; } } // fall through goto default; default: return -1; } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/InternalUtilities/ISetExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; namespace Roslyn.Utilities { internal static class ISetExtensions { public static bool AddAll<T>(this ISet<T> set, IEnumerable<T> values) { var result = false; foreach (var v in values) { result |= set.Add(v); } return result; } public static bool AddAll<T>(this ISet<T> set, ImmutableArray<T> values) { var result = false; foreach (var v in values) { result |= set.Add(v); } return result; } public static bool RemoveAll<T>(this ISet<T> set, IEnumerable<T> values) { var result = false; foreach (var v in values) { result |= set.Remove(v); } return result; } public static bool RemoveAll<T>(this ISet<T> set, ImmutableArray<T> values) { var result = false; foreach (var v in values) { result |= set.Remove(v); } 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.Collections.Generic; using System.Collections.Immutable; namespace Roslyn.Utilities { internal static class ISetExtensions { public static bool AddAll<T>(this ISet<T> set, IEnumerable<T> values) { var result = false; foreach (var v in values) { result |= set.Add(v); } return result; } public static bool AddAll<T>(this ISet<T> set, ImmutableArray<T> values) { var result = false; foreach (var v in values) { result |= set.Add(v); } return result; } public static bool RemoveAll<T>(this ISet<T> set, IEnumerable<T> values) { var result = false; foreach (var v in values) { result |= set.Remove(v); } return result; } public static bool RemoveAll<T>(this ISet<T> set, ImmutableArray<T> values) { var result = false; foreach (var v in values) { result |= set.Remove(v); } return result; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Test/Syntax/Parser/InterpolatedStringParsingTests.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 Roslyn.Test.Utilities Public Class InterpolatedStringParsingTests Inherits BasicTestBase <Fact> Public Sub EmptyString() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($"""") End Sub End Module") End Sub <Fact> Public Sub NoInterpolations() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, World!"") End Sub End Module") End Sub <Fact> Public Sub OnlyInterpolation() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""{""Hello, World!""}"") End Sub End Module") End Sub <Fact> Public Sub SimpleInterpolation() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, {name}!"") End Sub End Module") End Sub <Fact> Public Sub ParenthesizedInterpolation() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, {(firstName & lastName)}!"") End Sub End Module") End Sub <Fact> Public Sub ComplexInterpolation_QueryExpression() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, {From name In names Select name.Length}!"") End Sub End Module") End Sub <Fact> Public Sub EscapedBraces() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""{{ {x}, {y} }}"") End Sub End Module") End Sub <Fact> Public Sub EmbeddedBracesWorkaround() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""{""{""}{x}, {y}{""}""}"") End Sub End Module") End Sub <Fact> Public Sub AlignmentClause() ParseAndVerify( "Module Program Sub Main() Console.WriteLine(""Header 1 | Header 2 | Header 3"") Console.WriteLine($""{items(0),9}|{items(1),9}|{items(2),9}"") End Sub End Module") End Sub <Fact> Public Sub FormatStringClause() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""You owe: {balanceDue:C02}."") End Sub End Module") End Sub <Fact> Public Sub FormatStringClause_WithTwoColons() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""You owe: {balanceDue::C02}."") End Sub End Module") End Sub <Fact> Public Sub AlignmentClauseAndFormatClause() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""You owe: {balanceDue,10:C02}."") End Sub End Module") End Sub <Fact> Public Sub MultilineText() ParseAndVerify( "Module Program Sub Main() Console.WriteLine( $""Name: {name} Age: {age} ====="") End Sub End Module") End Sub <Fact> Public Sub ERR_InterpolationFormatWhitespace() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty:C02 }!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC37249: Format specifier may not contain trailing whitespace. Console.WriteLine($"Hello, {EventArgs.Empty:C02 }!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterAfterOpenBraceAndBeforeCloseBraceWithoutFormatClause() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, { EventArgs.Empty }!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, { ~ BC30201: Expression expected. Console.WriteLine($"Hello, { ~ BC30370: '}' expected. Console.WriteLine($"Hello, { ~ BC30648: String constants must end with a double quote. }!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterAlignmentClause() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty,-10 :C02}!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty,-10 ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty,-10 ~ BC30201: Expression expected. :C02}!") ~ BC30800: Method arguments must be enclosed in parentheses. :C02}!") ~ BC30648: String constants must end with a double quote. :C02}!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterAlignmentClauseCommaToken() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty, -10:C02}!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty, ~ BC30204: Integer constant expected. Console.WriteLine($"Hello, {EventArgs.Empty, ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty, ~ BC30035: Syntax error. -10:C02}!") ~ BC30201: Expression expected. -10:C02}!") ~ BC30800: Method arguments must be enclosed in parentheses. -10:C02}!") ~ BC30648: String constants must end with a double quote. -10:C02}!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterFormatClause() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty:C02 }!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty:C02 ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty:C02 ~ BC30648: String constants must end with a double quote. }!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterFormatClauseColonToken() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty: C02}!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty: ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty: ~ BC30201: Expression expected. C02}!") ~ BC30800: Method arguments must be enclosed in parentheses. C02}!") ~ BC30648: String constants must end with a double quote. C02}!") ~~~ </expected>) End Sub <Fact> Public Sub ErrorRecovery_DollarSignMissingDoubleQuote() Parse( "Module Program Sub Main() Console.WriteLine($) End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingClosingDoubleQuote() Parse( "Module Program Sub Main() Console.WriteLine($"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingCloseBrace() Parse( "Module Program Sub Main() Console.WriteLine($""{"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionWithAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{,5}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionWithFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{:C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionWithAlignmentAndFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{,5:C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionAndAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{,}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionAndAlignmentAndFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{,:}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword() Parse( "Module Program Sub Main() Console.WriteLine($""{For}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter() Parse( "Module Program Sub Main() Console.WriteLine($""{`}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 +}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{1,}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{1,&}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{1:}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5:}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingOpenBrace() Parse( "Module Program Sub Main() Console.WriteLine($""}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_DollarSignMissingDoubleQuote_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($ End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingClosingDoubleQuote_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingCloseBrace_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpression_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{For}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{`}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 +}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,&}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1:}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5:}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingOpenBrace_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{For"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{`"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 +"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1,"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1,&"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1:"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5:"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{For End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{` End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 + End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1, End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,& End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1: End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5: End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5 End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_FollowedByAColon() Parse( "Module Program Sub Main() Console.WriteLine($""{CStr(:C02}"") Console.WriteLine($""{CStr(1:C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_FollowedByATwoColons() Parse( "Module Program Sub Main() Console.WriteLine($""{CStr(::C02}"") Console.WriteLine($""{CStr(1::C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_ExtraCloseBraceFollowingInterpolationWithNoFormatClause() Parse( "Module Program Sub Main() Console.WriteLine($""{1}}"") End Sub End Module") End Sub <Fact, WorkItem(6341, "https://github.com/dotnet/roslyn/issues/6341")> Public Sub LineBreakInInterpolation_1() Parse( "Module Program Sub Main() Dim x = $""{ " + vbCr + vbCr + "1 }"" End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30201: Expression expected. Dim x = $"{ ~ BC30370: '}' expected. Dim x = $"{ ~ BC30801: Labels that are numbers must be followed by colons. 1 ~~ BC30648: String constants must end with a double quote. }" ~~ </expected>) End Sub <Fact, WorkItem(6341, "https://github.com/dotnet/roslyn/issues/6341")> Public Sub LineBreakInInterpolation_2() Parse( "Module Program Sub Main() Dim x = $""{ 1 " + vbCr + vbCr + " }"" End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30370: '}' expected. Dim x = $"{ 1 ~ BC30648: String constants must end with a double quote. }" ~~ </expected>) 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 Roslyn.Test.Utilities Public Class InterpolatedStringParsingTests Inherits BasicTestBase <Fact> Public Sub EmptyString() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($"""") End Sub End Module") End Sub <Fact> Public Sub NoInterpolations() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, World!"") End Sub End Module") End Sub <Fact> Public Sub OnlyInterpolation() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""{""Hello, World!""}"") End Sub End Module") End Sub <Fact> Public Sub SimpleInterpolation() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, {name}!"") End Sub End Module") End Sub <Fact> Public Sub ParenthesizedInterpolation() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, {(firstName & lastName)}!"") End Sub End Module") End Sub <Fact> Public Sub ComplexInterpolation_QueryExpression() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, {From name In names Select name.Length}!"") End Sub End Module") End Sub <Fact> Public Sub EscapedBraces() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""{{ {x}, {y} }}"") End Sub End Module") End Sub <Fact> Public Sub EmbeddedBracesWorkaround() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""{""{""}{x}, {y}{""}""}"") End Sub End Module") End Sub <Fact> Public Sub AlignmentClause() ParseAndVerify( "Module Program Sub Main() Console.WriteLine(""Header 1 | Header 2 | Header 3"") Console.WriteLine($""{items(0),9}|{items(1),9}|{items(2),9}"") End Sub End Module") End Sub <Fact> Public Sub FormatStringClause() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""You owe: {balanceDue:C02}."") End Sub End Module") End Sub <Fact> Public Sub FormatStringClause_WithTwoColons() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""You owe: {balanceDue::C02}."") End Sub End Module") End Sub <Fact> Public Sub AlignmentClauseAndFormatClause() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""You owe: {balanceDue,10:C02}."") End Sub End Module") End Sub <Fact> Public Sub MultilineText() ParseAndVerify( "Module Program Sub Main() Console.WriteLine( $""Name: {name} Age: {age} ====="") End Sub End Module") End Sub <Fact> Public Sub ERR_InterpolationFormatWhitespace() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty:C02 }!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC37249: Format specifier may not contain trailing whitespace. Console.WriteLine($"Hello, {EventArgs.Empty:C02 }!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterAfterOpenBraceAndBeforeCloseBraceWithoutFormatClause() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, { EventArgs.Empty }!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, { ~ BC30201: Expression expected. Console.WriteLine($"Hello, { ~ BC30370: '}' expected. Console.WriteLine($"Hello, { ~ BC30648: String constants must end with a double quote. }!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterAlignmentClause() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty,-10 :C02}!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty,-10 ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty,-10 ~ BC30201: Expression expected. :C02}!") ~ BC30800: Method arguments must be enclosed in parentheses. :C02}!") ~ BC30648: String constants must end with a double quote. :C02}!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterAlignmentClauseCommaToken() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty, -10:C02}!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty, ~ BC30204: Integer constant expected. Console.WriteLine($"Hello, {EventArgs.Empty, ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty, ~ BC30035: Syntax error. -10:C02}!") ~ BC30201: Expression expected. -10:C02}!") ~ BC30800: Method arguments must be enclosed in parentheses. -10:C02}!") ~ BC30648: String constants must end with a double quote. -10:C02}!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterFormatClause() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty:C02 }!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty:C02 ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty:C02 ~ BC30648: String constants must end with a double quote. }!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterFormatClauseColonToken() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty: C02}!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty: ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty: ~ BC30201: Expression expected. C02}!") ~ BC30800: Method arguments must be enclosed in parentheses. C02}!") ~ BC30648: String constants must end with a double quote. C02}!") ~~~ </expected>) End Sub <Fact> Public Sub ErrorRecovery_DollarSignMissingDoubleQuote() Parse( "Module Program Sub Main() Console.WriteLine($) End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingClosingDoubleQuote() Parse( "Module Program Sub Main() Console.WriteLine($"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingCloseBrace() Parse( "Module Program Sub Main() Console.WriteLine($""{"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionWithAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{,5}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionWithFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{:C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionWithAlignmentAndFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{,5:C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionAndAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{,}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionAndAlignmentAndFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{,:}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword() Parse( "Module Program Sub Main() Console.WriteLine($""{For}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter() Parse( "Module Program Sub Main() Console.WriteLine($""{`}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 +}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{1,}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{1,&}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{1:}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5:}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingOpenBrace() Parse( "Module Program Sub Main() Console.WriteLine($""}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_DollarSignMissingDoubleQuote_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($ End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingClosingDoubleQuote_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingCloseBrace_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpression_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{For}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{`}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 +}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,&}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1:}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5:}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingOpenBrace_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{For"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{`"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 +"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1,"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1,&"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1:"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5:"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{For End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{` End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 + End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1, End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,& End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1: End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5: End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5 End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_FollowedByAColon() Parse( "Module Program Sub Main() Console.WriteLine($""{CStr(:C02}"") Console.WriteLine($""{CStr(1:C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_FollowedByATwoColons() Parse( "Module Program Sub Main() Console.WriteLine($""{CStr(::C02}"") Console.WriteLine($""{CStr(1::C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_ExtraCloseBraceFollowingInterpolationWithNoFormatClause() Parse( "Module Program Sub Main() Console.WriteLine($""{1}}"") End Sub End Module") End Sub <Fact, WorkItem(6341, "https://github.com/dotnet/roslyn/issues/6341")> Public Sub LineBreakInInterpolation_1() Parse( "Module Program Sub Main() Dim x = $""{ " + vbCr + vbCr + "1 }"" End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30201: Expression expected. Dim x = $"{ ~ BC30370: '}' expected. Dim x = $"{ ~ BC30801: Labels that are numbers must be followed by colons. 1 ~~ BC30648: String constants must end with a double quote. }" ~~ </expected>) End Sub <Fact, WorkItem(6341, "https://github.com/dotnet/roslyn/issues/6341")> Public Sub LineBreakInInterpolation_2() Parse( "Module Program Sub Main() Dim x = $""{ 1 " + vbCr + vbCr + " }"" End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30370: '}' expected. Dim x = $"{ 1 ~ BC30648: String constants must end with a double quote. }" ~~ </expected>) End Sub End Class
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicCommandLineParserService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic <ExportLanguageService(GetType(ICommandLineParserService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicCommandLineParserService Implements ICommandLineParserService <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 Function Parse(arguments As IEnumerable(Of String), baseDirectory As String, isInteractive As Boolean, sdkDirectory As String) As CommandLineArguments Implements ICommandLineParserService.Parse #If SCRIPTING Then Dim parser = If(isInteractive, VisualBasicCommandLineParser.Interactive, VisualBasicCommandLineParser.Default) #Else Dim parser = VisualBasicCommandLineParser.Default #End If Return parser.Parse(arguments, baseDirectory, sdkDirectory) 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.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic <ExportLanguageService(GetType(ICommandLineParserService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicCommandLineParserService Implements ICommandLineParserService <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 Function Parse(arguments As IEnumerable(Of String), baseDirectory As String, isInteractive As Boolean, sdkDirectory As String) As CommandLineArguments Implements ICommandLineParserService.Parse #If SCRIPTING Then Dim parser = If(isInteractive, VisualBasicCommandLineParser.Interactive, VisualBasicCommandLineParser.Default) #Else Dim parser = VisualBasicCommandLineParser.Default #End If Return parser.Parse(arguments, baseDirectory, sdkDirectory) End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/TestUtilities/EditAndContinue/Extensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal static class Extensions { public static IEnumerable<RudeEditDiagnosticDescription> ToDescription(this IEnumerable<RudeEditDiagnostic> diagnostics, SourceText newSource, bool includeFirstLines) { return diagnostics.Select(d => new RudeEditDiagnosticDescription( d.Kind, d.Span == default ? null : newSource.ToString(d.Span), d.Arguments, firstLine: includeFirstLines ? newSource.Lines.GetLineFromPosition(d.Span.Start).ToString().Trim() : null)); } private const string LineSeparator = "\r\n"; public static IEnumerable<string> ToLines(this string str) { var i = 0; while (true) { var eoln = str.IndexOf(LineSeparator, i, StringComparison.Ordinal); if (eoln < 0) { yield return str.Substring(i); yield break; } yield return str.Substring(i, eoln - i); i = eoln + LineSeparator.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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal static class Extensions { public static IEnumerable<RudeEditDiagnosticDescription> ToDescription(this IEnumerable<RudeEditDiagnostic> diagnostics, SourceText newSource, bool includeFirstLines) { return diagnostics.Select(d => new RudeEditDiagnosticDescription( d.Kind, d.Span == default ? null : newSource.ToString(d.Span), d.Arguments, firstLine: includeFirstLines ? newSource.Lines.GetLineFromPosition(d.Span.Start).ToString().Trim() : null)); } private const string LineSeparator = "\r\n"; public static IEnumerable<string> ToLines(this string str) { var i = 0; while (true) { var eoln = str.IndexOf(LineSeparator, i, StringComparison.Ordinal); if (eoln < 0) { yield return str.Substring(i); yield break; } yield return str.Substring(i, eoln - i); i = eoln + LineSeparator.Length; } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/Core/Portable/Completion/CompletionRules.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Completion { /// <summary> /// Presentation and behavior rules for completion. /// </summary> public sealed class CompletionRules { /// <summary> /// True if the completion list should be dismissed if the user's typing causes it to filter /// and display no items. /// </summary> public bool DismissIfEmpty { get; } /// <summary> /// True if the list should be dismissed when the user deletes the last character in the span. /// </summary> public bool DismissIfLastCharacterDeleted { get; } /// <summary> /// The default set of typed characters that cause the selected item to be committed. /// Individual <see cref="CompletionItem"/>s can override this. /// </summary> public ImmutableArray<char> DefaultCommitCharacters { get; } /// <summary> /// The default rule that determines if the enter key is passed through to the editor after the selected item has been committed. /// Individual <see cref="CompletionItem"/>s can override this. /// </summary> public EnterKeyRule DefaultEnterKeyRule { get; } /// <summary> /// The rule determining how snippets work. /// </summary> public SnippetsRule SnippetsRule { get; } private CompletionRules( bool dismissIfEmpty, bool dismissIfLastCharacterDeleted, ImmutableArray<char> defaultCommitCharacters, EnterKeyRule defaultEnterKeyRule, SnippetsRule snippetsRule) { DismissIfEmpty = dismissIfEmpty; DismissIfLastCharacterDeleted = dismissIfLastCharacterDeleted; DefaultCommitCharacters = defaultCommitCharacters.NullToEmpty(); DefaultEnterKeyRule = defaultEnterKeyRule; SnippetsRule = snippetsRule; } /// <summary> /// Creates a new <see cref="CompletionRules"/> instance. /// </summary> /// <param name="dismissIfEmpty">True if the completion list should be dismissed if the user's typing causes it to filter and display no items.</param> /// <param name="dismissIfLastCharacterDeleted">True if the list should be dismissed when the user deletes the last character in the span.</param> /// <param name="defaultCommitCharacters">The default set of typed characters that cause the selected item to be committed.</param> /// <param name="defaultEnterKeyRule">The default rule that determines if the enter key is passed through to the editor after the selected item has been committed.</param> public static CompletionRules Create( bool dismissIfEmpty, bool dismissIfLastCharacterDeleted, ImmutableArray<char> defaultCommitCharacters, EnterKeyRule defaultEnterKeyRule) { return Create(dismissIfEmpty, dismissIfLastCharacterDeleted, defaultCommitCharacters, defaultEnterKeyRule, SnippetsRule.Default); } /// <summary> /// Creates a new <see cref="CompletionRules"/> instance. /// </summary> /// <param name="dismissIfEmpty">True if the completion list should be dismissed if the user's typing causes it to filter and display no items.</param> /// <param name="dismissIfLastCharacterDeleted">True if the list should be dismissed when the user deletes the last character in the span.</param> /// <param name="defaultCommitCharacters">The default set of typed characters that cause the selected item to be committed.</param> /// <param name="defaultEnterKeyRule">The default rule that determines if the enter key is passed through to the editor after the selected item has been committed.</param> /// <param name="snippetsRule">The rule that controls snippets behavior.</param> public static CompletionRules Create( bool dismissIfEmpty = false, bool dismissIfLastCharacterDeleted = false, ImmutableArray<char> defaultCommitCharacters = default, EnterKeyRule defaultEnterKeyRule = EnterKeyRule.Default, SnippetsRule snippetsRule = SnippetsRule.Default) { return new CompletionRules( dismissIfEmpty: dismissIfEmpty, dismissIfLastCharacterDeleted: dismissIfLastCharacterDeleted, defaultCommitCharacters: defaultCommitCharacters, defaultEnterKeyRule: defaultEnterKeyRule, snippetsRule: snippetsRule); } private CompletionRules With( Optional<bool> dismissIfEmpty = default, Optional<bool> dismissIfLastCharacterDeleted = default, Optional<ImmutableArray<char>> defaultCommitCharacters = default, Optional<EnterKeyRule> defaultEnterKeyRule = default, Optional<SnippetsRule> snippetsRule = default) { var newDismissIfEmpty = dismissIfEmpty.HasValue ? dismissIfEmpty.Value : DismissIfEmpty; var newDismissIfLastCharacterDeleted = dismissIfLastCharacterDeleted.HasValue ? dismissIfLastCharacterDeleted.Value : DismissIfLastCharacterDeleted; var newDefaultCommitCharacters = defaultCommitCharacters.HasValue ? defaultCommitCharacters.Value : DefaultCommitCharacters; var newDefaultEnterKeyRule = defaultEnterKeyRule.HasValue ? defaultEnterKeyRule.Value : DefaultEnterKeyRule; var newSnippetsRule = snippetsRule.HasValue ? snippetsRule.Value : SnippetsRule; if (newDismissIfEmpty == DismissIfEmpty && newDismissIfLastCharacterDeleted == DismissIfLastCharacterDeleted && newDefaultCommitCharacters == DefaultCommitCharacters && newDefaultEnterKeyRule == DefaultEnterKeyRule && newSnippetsRule == SnippetsRule) { return this; } else { return Create( newDismissIfEmpty, newDismissIfLastCharacterDeleted, newDefaultCommitCharacters, newDefaultEnterKeyRule, newSnippetsRule); } } /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DismissIfEmpty"/> property changed. /// </summary> public CompletionRules WithDismissIfEmpty(bool dismissIfEmpty) => With(dismissIfEmpty: dismissIfEmpty); /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DismissIfLastCharacterDeleted"/> property changed. /// </summary> public CompletionRules WithDismissIfLastCharacterDeleted(bool dismissIfLastCharacterDeleted) => With(dismissIfLastCharacterDeleted: dismissIfLastCharacterDeleted); /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DefaultCommitCharacters"/> property changed. /// </summary> public CompletionRules WithDefaultCommitCharacters(ImmutableArray<char> defaultCommitCharacters) => With(defaultCommitCharacters: defaultCommitCharacters); /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DefaultEnterKeyRule"/> property changed. /// </summary> public CompletionRules WithDefaultEnterKeyRule(EnterKeyRule defaultEnterKeyRule) => With(defaultEnterKeyRule: defaultEnterKeyRule); /// <summary> /// Creates a copy of the this <see cref="CompletionRules"/> with the <see cref="SnippetsRule"/> property changed. /// </summary> public CompletionRules WithSnippetsRule(SnippetsRule snippetsRule) => With(snippetsRule: snippetsRule); private static readonly ImmutableArray<char> s_defaultCommitKeys = ImmutableArray.Create( ' ', '{', '}', '[', ']', '(', ')', '.', ',', ':', ';', '+', '-', '*', '/', '%', '&', '|', '^', '!', '~', '=', '<', '>', '?', '@', '#', '\'', '\"', '\\'); /// <summary> /// The default <see cref="CompletionRules"/> if none is otherwise specified. /// </summary> public static readonly CompletionRules Default = new( dismissIfEmpty: false, dismissIfLastCharacterDeleted: false, defaultCommitCharacters: s_defaultCommitKeys, defaultEnterKeyRule: EnterKeyRule.Default, snippetsRule: SnippetsRule.Default); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Presentation and behavior rules for completion. /// </summary> public sealed class CompletionRules { /// <summary> /// True if the completion list should be dismissed if the user's typing causes it to filter /// and display no items. /// </summary> public bool DismissIfEmpty { get; } /// <summary> /// True if the list should be dismissed when the user deletes the last character in the span. /// </summary> public bool DismissIfLastCharacterDeleted { get; } /// <summary> /// The default set of typed characters that cause the selected item to be committed. /// Individual <see cref="CompletionItem"/>s can override this. /// </summary> public ImmutableArray<char> DefaultCommitCharacters { get; } /// <summary> /// The default rule that determines if the enter key is passed through to the editor after the selected item has been committed. /// Individual <see cref="CompletionItem"/>s can override this. /// </summary> public EnterKeyRule DefaultEnterKeyRule { get; } /// <summary> /// The rule determining how snippets work. /// </summary> public SnippetsRule SnippetsRule { get; } private CompletionRules( bool dismissIfEmpty, bool dismissIfLastCharacterDeleted, ImmutableArray<char> defaultCommitCharacters, EnterKeyRule defaultEnterKeyRule, SnippetsRule snippetsRule) { DismissIfEmpty = dismissIfEmpty; DismissIfLastCharacterDeleted = dismissIfLastCharacterDeleted; DefaultCommitCharacters = defaultCommitCharacters.NullToEmpty(); DefaultEnterKeyRule = defaultEnterKeyRule; SnippetsRule = snippetsRule; } /// <summary> /// Creates a new <see cref="CompletionRules"/> instance. /// </summary> /// <param name="dismissIfEmpty">True if the completion list should be dismissed if the user's typing causes it to filter and display no items.</param> /// <param name="dismissIfLastCharacterDeleted">True if the list should be dismissed when the user deletes the last character in the span.</param> /// <param name="defaultCommitCharacters">The default set of typed characters that cause the selected item to be committed.</param> /// <param name="defaultEnterKeyRule">The default rule that determines if the enter key is passed through to the editor after the selected item has been committed.</param> public static CompletionRules Create( bool dismissIfEmpty, bool dismissIfLastCharacterDeleted, ImmutableArray<char> defaultCommitCharacters, EnterKeyRule defaultEnterKeyRule) { return Create(dismissIfEmpty, dismissIfLastCharacterDeleted, defaultCommitCharacters, defaultEnterKeyRule, SnippetsRule.Default); } /// <summary> /// Creates a new <see cref="CompletionRules"/> instance. /// </summary> /// <param name="dismissIfEmpty">True if the completion list should be dismissed if the user's typing causes it to filter and display no items.</param> /// <param name="dismissIfLastCharacterDeleted">True if the list should be dismissed when the user deletes the last character in the span.</param> /// <param name="defaultCommitCharacters">The default set of typed characters that cause the selected item to be committed.</param> /// <param name="defaultEnterKeyRule">The default rule that determines if the enter key is passed through to the editor after the selected item has been committed.</param> /// <param name="snippetsRule">The rule that controls snippets behavior.</param> public static CompletionRules Create( bool dismissIfEmpty = false, bool dismissIfLastCharacterDeleted = false, ImmutableArray<char> defaultCommitCharacters = default, EnterKeyRule defaultEnterKeyRule = EnterKeyRule.Default, SnippetsRule snippetsRule = SnippetsRule.Default) { return new CompletionRules( dismissIfEmpty: dismissIfEmpty, dismissIfLastCharacterDeleted: dismissIfLastCharacterDeleted, defaultCommitCharacters: defaultCommitCharacters, defaultEnterKeyRule: defaultEnterKeyRule, snippetsRule: snippetsRule); } private CompletionRules With( Optional<bool> dismissIfEmpty = default, Optional<bool> dismissIfLastCharacterDeleted = default, Optional<ImmutableArray<char>> defaultCommitCharacters = default, Optional<EnterKeyRule> defaultEnterKeyRule = default, Optional<SnippetsRule> snippetsRule = default) { var newDismissIfEmpty = dismissIfEmpty.HasValue ? dismissIfEmpty.Value : DismissIfEmpty; var newDismissIfLastCharacterDeleted = dismissIfLastCharacterDeleted.HasValue ? dismissIfLastCharacterDeleted.Value : DismissIfLastCharacterDeleted; var newDefaultCommitCharacters = defaultCommitCharacters.HasValue ? defaultCommitCharacters.Value : DefaultCommitCharacters; var newDefaultEnterKeyRule = defaultEnterKeyRule.HasValue ? defaultEnterKeyRule.Value : DefaultEnterKeyRule; var newSnippetsRule = snippetsRule.HasValue ? snippetsRule.Value : SnippetsRule; if (newDismissIfEmpty == DismissIfEmpty && newDismissIfLastCharacterDeleted == DismissIfLastCharacterDeleted && newDefaultCommitCharacters == DefaultCommitCharacters && newDefaultEnterKeyRule == DefaultEnterKeyRule && newSnippetsRule == SnippetsRule) { return this; } else { return Create( newDismissIfEmpty, newDismissIfLastCharacterDeleted, newDefaultCommitCharacters, newDefaultEnterKeyRule, newSnippetsRule); } } /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DismissIfEmpty"/> property changed. /// </summary> public CompletionRules WithDismissIfEmpty(bool dismissIfEmpty) => With(dismissIfEmpty: dismissIfEmpty); /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DismissIfLastCharacterDeleted"/> property changed. /// </summary> public CompletionRules WithDismissIfLastCharacterDeleted(bool dismissIfLastCharacterDeleted) => With(dismissIfLastCharacterDeleted: dismissIfLastCharacterDeleted); /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DefaultCommitCharacters"/> property changed. /// </summary> public CompletionRules WithDefaultCommitCharacters(ImmutableArray<char> defaultCommitCharacters) => With(defaultCommitCharacters: defaultCommitCharacters); /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DefaultEnterKeyRule"/> property changed. /// </summary> public CompletionRules WithDefaultEnterKeyRule(EnterKeyRule defaultEnterKeyRule) => With(defaultEnterKeyRule: defaultEnterKeyRule); /// <summary> /// Creates a copy of the this <see cref="CompletionRules"/> with the <see cref="SnippetsRule"/> property changed. /// </summary> public CompletionRules WithSnippetsRule(SnippetsRule snippetsRule) => With(snippetsRule: snippetsRule); private static readonly ImmutableArray<char> s_defaultCommitKeys = ImmutableArray.Create( ' ', '{', '}', '[', ']', '(', ')', '.', ',', ':', ';', '+', '-', '*', '/', '%', '&', '|', '^', '!', '~', '=', '<', '>', '?', '@', '#', '\'', '\"', '\\'); /// <summary> /// The default <see cref="CompletionRules"/> if none is otherwise specified. /// </summary> public static readonly CompletionRules Default = new( dismissIfEmpty: false, dismissIfLastCharacterDeleted: false, defaultCommitCharacters: s_defaultCommitKeys, defaultEnterKeyRule: EnterKeyRule.Default, snippetsRule: SnippetsRule.Default); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractTriviaDataFactory.Whitespace.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract partial class AbstractTriviaDataFactory { /// <summary> /// represents a general trivia between two tokens. slightly more expensive than others since it /// needs to calculate stuff unlike other cases /// </summary> protected class Whitespace : TriviaData { private readonly bool _elastic; public Whitespace(SyntaxFormattingOptions options, int space, bool elastic, string language) : this(options, lineBreaks: 0, indentation: space, elastic: elastic, language: language) { Contract.ThrowIfFalse(space >= 0); } public Whitespace(SyntaxFormattingOptions options, int lineBreaks, int indentation, bool elastic, string language) : base(options, language) { _elastic = elastic; // space and line breaks can be negative during formatting. but at the end, should be normalized // to >= 0 this.LineBreaks = lineBreaks; this.Spaces = indentation; } public override bool TreatAsElastic => _elastic; public override bool IsWhitespaceOnlyTrivia => true; public override bool ContainsChanges => false; public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules) { if (this.LineBreaks == 0 && this.Spaces == space) { return this; } return new ModifiedWhitespace(this.Options, this, /*lineBreak*/0, space, elastic: false, language: this.Language); } public override TriviaData WithLine(int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { Contract.ThrowIfFalse(line > 0); if (this.LineBreaks == line && this.Spaces == indentation) { return this; } return new ModifiedWhitespace(this.Options, this, line, indentation, elastic: false, language: this.Language); } public override TriviaData WithIndentation( int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { if (this.Spaces == indentation) { return this; } return new ModifiedWhitespace(this.Options, this, this.LineBreaks, indentation, elastic: false, language: this.Language); } public override void Format( FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) { // nothing changed, nothing to format } public override IEnumerable<TextChange> GetTextChanges(TextSpan span) => throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract partial class AbstractTriviaDataFactory { /// <summary> /// represents a general trivia between two tokens. slightly more expensive than others since it /// needs to calculate stuff unlike other cases /// </summary> protected class Whitespace : TriviaData { private readonly bool _elastic; public Whitespace(SyntaxFormattingOptions options, int space, bool elastic, string language) : this(options, lineBreaks: 0, indentation: space, elastic: elastic, language: language) { Contract.ThrowIfFalse(space >= 0); } public Whitespace(SyntaxFormattingOptions options, int lineBreaks, int indentation, bool elastic, string language) : base(options, language) { _elastic = elastic; // space and line breaks can be negative during formatting. but at the end, should be normalized // to >= 0 this.LineBreaks = lineBreaks; this.Spaces = indentation; } public override bool TreatAsElastic => _elastic; public override bool IsWhitespaceOnlyTrivia => true; public override bool ContainsChanges => false; public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules) { if (this.LineBreaks == 0 && this.Spaces == space) { return this; } return new ModifiedWhitespace(this.Options, this, /*lineBreak*/0, space, elastic: false, language: this.Language); } public override TriviaData WithLine(int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { Contract.ThrowIfFalse(line > 0); if (this.LineBreaks == line && this.Spaces == indentation) { return this; } return new ModifiedWhitespace(this.Options, this, line, indentation, elastic: false, language: this.Language); } public override TriviaData WithIndentation( int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { if (this.Spaces == indentation) { return this; } return new ModifiedWhitespace(this.Options, this, this.LineBreaks, indentation, elastic: false, language: this.Language); } public override void Format( FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) { // nothing changed, nothing to format } public override IEnumerable<TextChange> GetTextChanges(TextSpan span) => throw new NotImplementedException(); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/VisualBasic/Impl/Options/IntelliSenseOptionPage.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.Runtime.InteropServices Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options <Guid(Guids.VisualBasicOptionPageIntelliSenseIdString)> Friend Class IntelliSenseOptionPage Inherits AbstractOptionPage Protected Overrides Function CreateOptionPage(serviceProvider As IServiceProvider, optionStore As OptionStore) As AbstractOptionPageControl Return New IntelliSenseOptionPageControl(optionStore) 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 Imports System.Runtime.InteropServices Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options <Guid(Guids.VisualBasicOptionPageIntelliSenseIdString)> Friend Class IntelliSenseOptionPage Inherits AbstractOptionPage Protected Overrides Function CreateOptionPage(serviceProvider As IServiceProvider, optionStore As OptionStore) As AbstractOptionPageControl Return New IntelliSenseOptionPageControl(optionStore) End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/ReferenceManager/MergedAliases.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class MergedAliases { public ArrayBuilder<string>? AliasesOpt; public ArrayBuilder<string>? RecursiveAliasesOpt; public ArrayBuilder<MetadataReference>? MergedReferencesOpt; /// <summary> /// Adds aliases of a specified reference to the merged set of aliases. /// Consider the following special cases: /// /// o {} + {} = {} /// If neither reference has any aliases then the result has no aliases. /// /// o {A} + {} = {A, global} /// {} + {A} = {A, global} /// /// If one and only one of the references has aliases we add the global alias since the /// referenced declarations should now be accessible both via existing aliases /// as well as unqualified. /// /// o {A, A} + {A, B, B} = {A, A, B, B} /// We preserve dups in each alias array, but avoid making more dups when merging. /// </summary> internal void Merge(MetadataReference reference) { ArrayBuilder<string> aliases; if (reference.Properties.HasRecursiveAliases) { if (RecursiveAliasesOpt == null) { RecursiveAliasesOpt = ArrayBuilder<string>.GetInstance(); RecursiveAliasesOpt.AddRange(reference.Properties.Aliases); return; } aliases = RecursiveAliasesOpt; } else { if (AliasesOpt == null) { AliasesOpt = ArrayBuilder<string>.GetInstance(); AliasesOpt.AddRange(reference.Properties.Aliases); return; } aliases = AliasesOpt; } Merge( aliases: aliases, newAliases: reference.Properties.Aliases); (MergedReferencesOpt ??= ArrayBuilder<MetadataReference>.GetInstance()).Add(reference); } internal static void Merge(ArrayBuilder<string> aliases, ImmutableArray<string> newAliases) { if (aliases.Count == 0 ^ newAliases.IsEmpty) { AddNonIncluded(aliases, MetadataReferenceProperties.GlobalAlias); } AddNonIncluded(aliases, newAliases); } internal static ImmutableArray<string> Merge(ImmutableArray<string> aliasesOpt, ImmutableArray<string> newAliases) { if (aliasesOpt.IsDefault) { return newAliases; } var result = ArrayBuilder<string>.GetInstance(aliasesOpt.Length); result.AddRange(aliasesOpt); Merge(result, newAliases); return result.ToImmutableAndFree(); } private static void AddNonIncluded(ArrayBuilder<string> builder, string item) { if (!builder.Contains(item)) { builder.Add(item); } } private static void AddNonIncluded(ArrayBuilder<string> builder, ImmutableArray<string> items) { int originalCount = builder.Count; foreach (var item in items) { if (builder.IndexOf(item, 0, originalCount) < 0) { builder.Add(item); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class MergedAliases { public ArrayBuilder<string>? AliasesOpt; public ArrayBuilder<string>? RecursiveAliasesOpt; public ArrayBuilder<MetadataReference>? MergedReferencesOpt; /// <summary> /// Adds aliases of a specified reference to the merged set of aliases. /// Consider the following special cases: /// /// o {} + {} = {} /// If neither reference has any aliases then the result has no aliases. /// /// o {A} + {} = {A, global} /// {} + {A} = {A, global} /// /// If one and only one of the references has aliases we add the global alias since the /// referenced declarations should now be accessible both via existing aliases /// as well as unqualified. /// /// o {A, A} + {A, B, B} = {A, A, B, B} /// We preserve dups in each alias array, but avoid making more dups when merging. /// </summary> internal void Merge(MetadataReference reference) { ArrayBuilder<string> aliases; if (reference.Properties.HasRecursiveAliases) { if (RecursiveAliasesOpt == null) { RecursiveAliasesOpt = ArrayBuilder<string>.GetInstance(); RecursiveAliasesOpt.AddRange(reference.Properties.Aliases); return; } aliases = RecursiveAliasesOpt; } else { if (AliasesOpt == null) { AliasesOpt = ArrayBuilder<string>.GetInstance(); AliasesOpt.AddRange(reference.Properties.Aliases); return; } aliases = AliasesOpt; } Merge( aliases: aliases, newAliases: reference.Properties.Aliases); (MergedReferencesOpt ??= ArrayBuilder<MetadataReference>.GetInstance()).Add(reference); } internal static void Merge(ArrayBuilder<string> aliases, ImmutableArray<string> newAliases) { if (aliases.Count == 0 ^ newAliases.IsEmpty) { AddNonIncluded(aliases, MetadataReferenceProperties.GlobalAlias); } AddNonIncluded(aliases, newAliases); } internal static ImmutableArray<string> Merge(ImmutableArray<string> aliasesOpt, ImmutableArray<string> newAliases) { if (aliasesOpt.IsDefault) { return newAliases; } var result = ArrayBuilder<string>.GetInstance(aliasesOpt.Length); result.AddRange(aliasesOpt); Merge(result, newAliases); return result.ToImmutableAndFree(); } private static void AddNonIncluded(ArrayBuilder<string> builder, string item) { if (!builder.Contains(item)) { builder.Add(item); } } private static void AddNonIncluded(ArrayBuilder<string> builder, ImmutableArray<string> items) { int originalCount = builder.Count; foreach (var item in items) { if (builder.IndexOf(item, 0, originalCount) < 0) { builder.Add(item); } } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/EditorVerifierInProcess.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Extensibility.Testing; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.LanguageServices; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.InProcess { [TestService] internal partial class EditorVerifierInProcess { public async Task CurrentLineTextAsync( string expectedText, bool assertCaretPosition = false, CancellationToken cancellationToken = default) { if (assertCaretPosition) { await CurrentLineTextAndAssertCaretPositionAsync(expectedText, cancellationToken); } else { var lineText = await TestServices.Editor.GetCurrentLineTextAsync(cancellationToken); Assert.Equal(expectedText, lineText); } } private async Task CurrentLineTextAndAssertCaretPositionAsync( string expectedText, CancellationToken cancellationToken) { var expectedCaretIndex = expectedText.IndexOf("$$"); if (expectedCaretIndex < 0) { throw new ArgumentException("Expected caret position to be specified with $$", nameof(expectedText)); } var expectedCaretMarkupEndIndex = expectedCaretIndex + "$$".Length; var expectedTextBeforeCaret = expectedText.Substring(0, expectedCaretIndex); var expectedTextAfterCaret = expectedText.Substring(expectedCaretMarkupEndIndex); var lineText = await TestServices.Editor.GetCurrentLineTextAsync(cancellationToken); var lineTextBeforeCaret = await TestServices.Editor.GetLineTextBeforeCaretAsync(cancellationToken); var lineTextAfterCaret = await TestServices.Editor.GetLineTextAfterCaretAsync(cancellationToken); Assert.Equal(expectedTextBeforeCaret, lineTextBeforeCaret); Assert.Equal(expectedTextAfterCaret, lineTextAfterCaret); Assert.Equal(expectedTextBeforeCaret.Length + expectedTextAfterCaret.Length, lineText.Length); } public async Task TextContainsAsync( string expectedText, bool assertCaretPosition = false, CancellationToken cancellationToken = default) { if (assertCaretPosition) { await TextContainsAndAssertCaretPositionAsync(expectedText, cancellationToken); } else { var view = await TestServices.Editor.GetActiveTextViewAsync(cancellationToken); var editorText = view.TextSnapshot.GetText(); Assert.Contains(expectedText, editorText); } } private async Task TextContainsAndAssertCaretPositionAsync( string expectedText, CancellationToken cancellationToken) { var caretStartIndex = expectedText.IndexOf("$$"); if (caretStartIndex < 0) { throw new ArgumentException("Expected caret position to be specified with $$", nameof(expectedText)); } var caretEndIndex = caretStartIndex + "$$".Length; var expectedTextBeforeCaret = expectedText[..caretStartIndex]; var expectedTextAfterCaret = expectedText[caretEndIndex..]; var expectedTextWithoutCaret = expectedTextBeforeCaret + expectedTextAfterCaret; var view = await TestServices.Editor.GetActiveTextViewAsync(cancellationToken); var editorText = view.TextSnapshot.GetText(); Assert.Contains(expectedTextWithoutCaret, editorText); var index = editorText.IndexOf(expectedTextWithoutCaret); var caretPosition = await TestServices.Editor.GetCaretPositionAsync(cancellationToken); Assert.Equal(caretStartIndex + index, caretPosition); } public async Task CodeActionAsync( string expectedItem, bool applyFix = false, bool verifyNotShowing = false, bool ensureExpectedItemsAreOrdered = false, FixAllScope? fixAllScope = null, bool blockUntilComplete = true, CancellationToken cancellationToken = default) { var expectedItems = new[] { expectedItem }; bool? applied; do { cancellationToken.ThrowIfCancellationRequested(); applied = await CodeActionsAsync(expectedItems, applyFix ? expectedItem : null, verifyNotShowing, ensureExpectedItemsAreOrdered, fixAllScope, blockUntilComplete, cancellationToken); } while (applied is false); } /// <returns> /// <list type="bullet"> /// <item><description><see langword="true"/> if <paramref name="applyFix"/> is specified and the fix is successfully applied</description></item> /// <item><description><see langword="false"/> if <paramref name="applyFix"/> is specified but the fix is not successfully applied</description></item> /// <item><description><see langword="null"/> if <paramref name="applyFix"/> is false, so there is no fix to apply</description></item> /// </list> /// </returns> public async Task<bool?> CodeActionsAsync( IEnumerable<string> expectedItems, string? applyFix = null, bool verifyNotShowing = false, bool ensureExpectedItemsAreOrdered = false, FixAllScope? fixAllScope = null, bool blockUntilComplete = true, CancellationToken cancellationToken = default) { var events = new List<WorkspaceChangeEventArgs>(); void WorkspaceChangedHandler(object sender, WorkspaceChangeEventArgs e) => events.Add(e); var workspace = await TestServices.Shell.GetComponentModelServiceAsync<VisualStudioWorkspace>(cancellationToken); using var workspaceEventRestorer = WithWorkspaceChangedHandler(workspace, WorkspaceChangedHandler); await TestServices.Editor.ShowLightBulbAsync(cancellationToken); if (verifyNotShowing) { await CodeActionsNotShowingAsync(cancellationToken); return null; } var actions = await TestServices.Editor.GetLightBulbActionsAsync(cancellationToken); if (expectedItems != null && expectedItems.Any()) { if (ensureExpectedItemsAreOrdered) { TestUtilities.ThrowIfExpectedItemNotFoundInOrder( actions, expectedItems); } else { TestUtilities.ThrowIfExpectedItemNotFound( actions, expectedItems); } } if (fixAllScope.HasValue) { Assumes.Present(applyFix); } if (!RoslynString.IsNullOrEmpty(applyFix)) { var codeActionLogger = new CodeActionLogger(); using var loggerRestorer = WithLogger(AggregateLogger.AddOrReplace(codeActionLogger, Logger.GetLogger(), logger => logger is CodeActionLogger)); var result = await TestServices.Editor.ApplyLightBulbActionAsync(applyFix, fixAllScope, blockUntilComplete, cancellationToken); if (blockUntilComplete) { // wait for action to complete await TestServices.Workspace.WaitForAllAsyncOperationsAsync( new[] { FeatureAttribute.Workspace, FeatureAttribute.LightBulb, }, cancellationToken); if (codeActionLogger.Messages.Any()) { foreach (var e in events) { codeActionLogger.Messages.Add($"{e.OldSolution.WorkspaceVersion} to {e.NewSolution.WorkspaceVersion}: {e.Kind} {e.DocumentId}"); } } AssertEx.EqualOrDiff( "", string.Join(Environment.NewLine, codeActionLogger.Messages)); } return result; } return null; } public async Task CodeActionsNotShowingAsync(CancellationToken cancellationToken) { if (await TestServices.Editor.IsLightBulbSessionExpandedAsync(cancellationToken)) { throw new InvalidOperationException("Expected no light bulb session, but one was found."); } } public async Task CaretPositionAsync(int expectedCaretPosition, CancellationToken cancellationToken) { Assert.Equal(expectedCaretPosition, await TestServices.Editor.GetCaretPositionAsync(cancellationToken)); } public async Task ErrorTagsAsync(string[] expectedTags, CancellationToken cancellationToken) { await TestServices.Workspace.WaitForAllAsyncOperationsAsync( new[] { FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.ErrorSquiggles }, cancellationToken); var actualTags = await TestServices.Editor.GetErrorTagsAsync(cancellationToken); AssertEx.EqualOrDiff( string.Join(Environment.NewLine, expectedTags), string.Join(Environment.NewLine, actualTags)); } private static WorkspaceEventRestorer WithWorkspaceChangedHandler(Workspace workspace, EventHandler<WorkspaceChangeEventArgs> eventHandler) { workspace.WorkspaceChanged += eventHandler; return new WorkspaceEventRestorer(workspace, eventHandler); } private static LoggerRestorer WithLogger(ILogger logger) { return new LoggerRestorer(Logger.SetLogger(logger)); } private sealed class CodeActionLogger : ILogger { public List<string> Messages { get; } = new(); public bool IsEnabled(FunctionId functionId) { return functionId == FunctionId.Workspace_ApplyChanges; } public void Log(FunctionId functionId, LogMessage logMessage) { if (functionId != FunctionId.Workspace_ApplyChanges) return; lock (Messages) { Messages.Add(logMessage.GetMessage()); } } public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken) { } public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken) { } } private readonly struct WorkspaceEventRestorer : IDisposable { private readonly Workspace _workspace; private readonly EventHandler<WorkspaceChangeEventArgs> _eventHandler; public WorkspaceEventRestorer(Workspace workspace, EventHandler<WorkspaceChangeEventArgs> eventHandler) { _workspace = workspace; _eventHandler = eventHandler; } public void Dispose() { _workspace.WorkspaceChanged -= _eventHandler; } } private readonly struct LoggerRestorer : IDisposable { private readonly ILogger? _logger; public LoggerRestorer(ILogger? logger) { _logger = logger; } public void Dispose() { Logger.SetLogger(_logger); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Extensibility.Testing; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.LanguageServices; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.InProcess { [TestService] internal partial class EditorVerifierInProcess { public async Task CurrentLineTextAsync( string expectedText, bool assertCaretPosition = false, CancellationToken cancellationToken = default) { if (assertCaretPosition) { await CurrentLineTextAndAssertCaretPositionAsync(expectedText, cancellationToken); } else { var lineText = await TestServices.Editor.GetCurrentLineTextAsync(cancellationToken); Assert.Equal(expectedText, lineText); } } private async Task CurrentLineTextAndAssertCaretPositionAsync( string expectedText, CancellationToken cancellationToken) { var expectedCaretIndex = expectedText.IndexOf("$$"); if (expectedCaretIndex < 0) { throw new ArgumentException("Expected caret position to be specified with $$", nameof(expectedText)); } var expectedCaretMarkupEndIndex = expectedCaretIndex + "$$".Length; var expectedTextBeforeCaret = expectedText.Substring(0, expectedCaretIndex); var expectedTextAfterCaret = expectedText.Substring(expectedCaretMarkupEndIndex); var lineText = await TestServices.Editor.GetCurrentLineTextAsync(cancellationToken); var lineTextBeforeCaret = await TestServices.Editor.GetLineTextBeforeCaretAsync(cancellationToken); var lineTextAfterCaret = await TestServices.Editor.GetLineTextAfterCaretAsync(cancellationToken); Assert.Equal(expectedTextBeforeCaret, lineTextBeforeCaret); Assert.Equal(expectedTextAfterCaret, lineTextAfterCaret); Assert.Equal(expectedTextBeforeCaret.Length + expectedTextAfterCaret.Length, lineText.Length); } public async Task TextContainsAsync( string expectedText, bool assertCaretPosition = false, CancellationToken cancellationToken = default) { if (assertCaretPosition) { await TextContainsAndAssertCaretPositionAsync(expectedText, cancellationToken); } else { var view = await TestServices.Editor.GetActiveTextViewAsync(cancellationToken); var editorText = view.TextSnapshot.GetText(); Assert.Contains(expectedText, editorText); } } private async Task TextContainsAndAssertCaretPositionAsync( string expectedText, CancellationToken cancellationToken) { var caretStartIndex = expectedText.IndexOf("$$"); if (caretStartIndex < 0) { throw new ArgumentException("Expected caret position to be specified with $$", nameof(expectedText)); } var caretEndIndex = caretStartIndex + "$$".Length; var expectedTextBeforeCaret = expectedText[..caretStartIndex]; var expectedTextAfterCaret = expectedText[caretEndIndex..]; var expectedTextWithoutCaret = expectedTextBeforeCaret + expectedTextAfterCaret; var view = await TestServices.Editor.GetActiveTextViewAsync(cancellationToken); var editorText = view.TextSnapshot.GetText(); Assert.Contains(expectedTextWithoutCaret, editorText); var index = editorText.IndexOf(expectedTextWithoutCaret); var caretPosition = await TestServices.Editor.GetCaretPositionAsync(cancellationToken); Assert.Equal(caretStartIndex + index, caretPosition); } public async Task CodeActionAsync( string expectedItem, bool applyFix = false, bool verifyNotShowing = false, bool ensureExpectedItemsAreOrdered = false, FixAllScope? fixAllScope = null, bool blockUntilComplete = true, CancellationToken cancellationToken = default) { var expectedItems = new[] { expectedItem }; bool? applied; do { cancellationToken.ThrowIfCancellationRequested(); applied = await CodeActionsAsync(expectedItems, applyFix ? expectedItem : null, verifyNotShowing, ensureExpectedItemsAreOrdered, fixAllScope, blockUntilComplete, cancellationToken); } while (applied is false); } /// <returns> /// <list type="bullet"> /// <item><description><see langword="true"/> if <paramref name="applyFix"/> is specified and the fix is successfully applied</description></item> /// <item><description><see langword="false"/> if <paramref name="applyFix"/> is specified but the fix is not successfully applied</description></item> /// <item><description><see langword="null"/> if <paramref name="applyFix"/> is false, so there is no fix to apply</description></item> /// </list> /// </returns> public async Task<bool?> CodeActionsAsync( IEnumerable<string> expectedItems, string? applyFix = null, bool verifyNotShowing = false, bool ensureExpectedItemsAreOrdered = false, FixAllScope? fixAllScope = null, bool blockUntilComplete = true, CancellationToken cancellationToken = default) { var events = new List<WorkspaceChangeEventArgs>(); void WorkspaceChangedHandler(object sender, WorkspaceChangeEventArgs e) => events.Add(e); var workspace = await TestServices.Shell.GetComponentModelServiceAsync<VisualStudioWorkspace>(cancellationToken); using var workspaceEventRestorer = WithWorkspaceChangedHandler(workspace, WorkspaceChangedHandler); await TestServices.Editor.ShowLightBulbAsync(cancellationToken); if (verifyNotShowing) { await CodeActionsNotShowingAsync(cancellationToken); return null; } var actions = await TestServices.Editor.GetLightBulbActionsAsync(cancellationToken); if (expectedItems != null && expectedItems.Any()) { if (ensureExpectedItemsAreOrdered) { TestUtilities.ThrowIfExpectedItemNotFoundInOrder( actions, expectedItems); } else { TestUtilities.ThrowIfExpectedItemNotFound( actions, expectedItems); } } if (fixAllScope.HasValue) { Assumes.Present(applyFix); } if (!RoslynString.IsNullOrEmpty(applyFix)) { var codeActionLogger = new CodeActionLogger(); using var loggerRestorer = WithLogger(AggregateLogger.AddOrReplace(codeActionLogger, Logger.GetLogger(), logger => logger is CodeActionLogger)); var result = await TestServices.Editor.ApplyLightBulbActionAsync(applyFix, fixAllScope, blockUntilComplete, cancellationToken); if (blockUntilComplete) { // wait for action to complete await TestServices.Workspace.WaitForAllAsyncOperationsAsync( new[] { FeatureAttribute.Workspace, FeatureAttribute.LightBulb, }, cancellationToken); if (codeActionLogger.Messages.Any()) { foreach (var e in events) { codeActionLogger.Messages.Add($"{e.OldSolution.WorkspaceVersion} to {e.NewSolution.WorkspaceVersion}: {e.Kind} {e.DocumentId}"); } } AssertEx.EqualOrDiff( "", string.Join(Environment.NewLine, codeActionLogger.Messages)); } return result; } return null; } public async Task CodeActionsNotShowingAsync(CancellationToken cancellationToken) { if (await TestServices.Editor.IsLightBulbSessionExpandedAsync(cancellationToken)) { throw new InvalidOperationException("Expected no light bulb session, but one was found."); } } public async Task CaretPositionAsync(int expectedCaretPosition, CancellationToken cancellationToken) { Assert.Equal(expectedCaretPosition, await TestServices.Editor.GetCaretPositionAsync(cancellationToken)); } public async Task ErrorTagsAsync(string[] expectedTags, CancellationToken cancellationToken) { await TestServices.Workspace.WaitForAllAsyncOperationsAsync( new[] { FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.ErrorSquiggles }, cancellationToken); var actualTags = await TestServices.Editor.GetErrorTagsAsync(cancellationToken); AssertEx.EqualOrDiff( string.Join(Environment.NewLine, expectedTags), string.Join(Environment.NewLine, actualTags)); } private static WorkspaceEventRestorer WithWorkspaceChangedHandler(Workspace workspace, EventHandler<WorkspaceChangeEventArgs> eventHandler) { workspace.WorkspaceChanged += eventHandler; return new WorkspaceEventRestorer(workspace, eventHandler); } private static LoggerRestorer WithLogger(ILogger logger) { return new LoggerRestorer(Logger.SetLogger(logger)); } private sealed class CodeActionLogger : ILogger { public List<string> Messages { get; } = new(); public bool IsEnabled(FunctionId functionId) { return functionId == FunctionId.Workspace_ApplyChanges; } public void Log(FunctionId functionId, LogMessage logMessage) { if (functionId != FunctionId.Workspace_ApplyChanges) return; lock (Messages) { Messages.Add(logMessage.GetMessage()); } } public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken) { } public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken) { } } private readonly struct WorkspaceEventRestorer : IDisposable { private readonly Workspace _workspace; private readonly EventHandler<WorkspaceChangeEventArgs> _eventHandler; public WorkspaceEventRestorer(Workspace workspace, EventHandler<WorkspaceChangeEventArgs> eventHandler) { _workspace = workspace; _eventHandler = eventHandler; } public void Dispose() { _workspace.WorkspaceChanged -= _eventHandler; } } private readonly struct LoggerRestorer : IDisposable { private readonly ILogger? _logger; public LoggerRestorer(ILogger? logger) { _logger = logger; } public void Dispose() { Logger.SetLogger(_logger); } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/Core/Portable/Shared/Utilities/ProgressTracker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// Utility class that can be used to track the progress of an operation in a threadsafe manner. /// </summary> internal class ProgressTracker : IProgressTracker { private string _description; private int _completedItems; private int _totalItems; private readonly Action<string, int, int> _updateActionOpt; public ProgressTracker() : this(null) { } public ProgressTracker(Action<string, int, int> updateActionOpt) => _updateActionOpt = updateActionOpt; public string Description { get => _description; set { _description = value; Update(); } } public int CompletedItems => _completedItems; public int TotalItems => _totalItems; public void AddItems(int count) { Interlocked.Add(ref _totalItems, count); Update(); } public void ItemCompleted() { Interlocked.Increment(ref _completedItems); Update(); } public void Clear() { _totalItems = 0; _completedItems = 0; _description = null; Update(); } private void Update() => _updateActionOpt?.Invoke(_description, _completedItems, _totalItems); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// Utility class that can be used to track the progress of an operation in a threadsafe manner. /// </summary> internal class ProgressTracker : IProgressTracker { private string _description; private int _completedItems; private int _totalItems; private readonly Action<string, int, int> _updateActionOpt; public ProgressTracker() : this(null) { } public ProgressTracker(Action<string, int, int> updateActionOpt) => _updateActionOpt = updateActionOpt; public string Description { get => _description; set { _description = value; Update(); } } public int CompletedItems => _completedItems; public int TotalItems => _totalItems; public void AddItems(int count) { Interlocked.Add(ref _totalItems, count); Update(); } public void ItemCompleted() { Interlocked.Increment(ref _completedItems); Update(); } public void Clear() { _totalItems = 0; _completedItems = 0; _description = null; Update(); } private void Update() => _updateActionOpt?.Invoke(_description, _completedItems, _totalItems); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Test/CodeModel/AbstractFileCodeModelTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractFileCodeModelTests Inherits AbstractCodeModelObjectTests(Of EnvDTE80.FileCodeModel2) Protected Async Function TestOperation(code As XElement, expectedCode As XElement, operation As Action(Of EnvDTE80.FileCodeModel2)) As Task WpfTestRunner.RequireWpfFact($"Test calls {NameOf(Me.TestOperation)} which means we're creating new {NameOf(EnvDTE.CodeModel)} elements.") Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) operation(fileCodeModel) Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString() Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim()) End Using Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) fileCodeModel.BeginBatch() operation(fileCodeModel) fileCodeModel.EndBatch() Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString() Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim()) End Using End Function Protected Sub TestOperation(code As XElement, operation As Action(Of EnvDTE80.FileCodeModel2)) Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) operation(fileCodeModel) End Using Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) fileCodeModel.BeginBatch() operation(fileCodeModel) fileCodeModel.EndBatch() End Using End Sub Protected Overrides Sub TestChildren(code As XElement, ParamArray expectedChildren() As Action(Of Object)) TestOperation(code, Sub(fileCodeModel) Dim children = fileCodeModel.CodeElements Assert.Equal(expectedChildren.Length, children.Count) For i = 1 To children.Count expectedChildren(i - 1)(children.Item(i)) Next End Sub) End Sub Protected Overrides Async Function TestAddAttribute(code As XElement, expectedCode As XElement, data As AttributeData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newAttribute = fileCodeModel.AddAttribute(data.Name, data.Value, data.Position) Assert.NotNull(newAttribute) Assert.Equal(data.Name, newAttribute.Name) End Sub) End Function Protected Overrides Async Function TestAddClass(code As XElement, expectedCode As XElement, data As ClassData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newClass = fileCodeModel.AddClass(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access) Assert.NotNull(newClass) Assert.Equal(data.Name, newClass.Name) End Sub) End Function Protected Overrides Async Function TestAddDelegate(code As XElement, expectedCode As XElement, data As DelegateData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newDelegate = fileCodeModel.AddDelegate(data.Name, data.Type, data.Position, data.Access) Assert.NotNull(newDelegate) Assert.Equal(data.Name, newDelegate.Name) End Sub) End Function Protected Overrides Async Function TestAddEnum(code As XElement, expectedCode As XElement, data As EnumData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newEnum = fileCodeModel.AddEnum(data.Name, data.Position, data.Base, data.Access) Assert.NotNull(newEnum) Assert.Equal(data.Name, newEnum.Name) End Sub) End Function Protected Overrides Async Function TestAddFunction(code As XElement, expectedCode As XElement, data As FunctionData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Assert.Throws(Of System.Runtime.InteropServices.COMException)( Sub() fileCodeModel.AddFunction(data.Name, data.Kind, data.Type, data.Position, data.Access) End Sub) End Sub) End Function Protected Overrides Async Function TestAddImport(code As XElement, expectedCode As XElement, data As ImportData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newImport = fileCodeModel.AddImport(data.Namespace, data.Position, data.Alias) Assert.NotNull(newImport) Assert.Equal(data.Namespace, newImport.Namespace) If data.Alias IsNot Nothing Then Assert.Equal(data.Alias, newImport.Alias) End If End Sub) End Function Protected Overrides Async Function TestAddInterface(code As XElement, expectedCode As XElement, data As InterfaceData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newInterface = fileCodeModel.AddInterface(data.Name, data.Position, data.Bases, data.Access) Assert.NotNull(newInterface) Assert.Equal(data.Name, newInterface.Name) End Sub) End Function Protected Overrides Async Function TestAddNamespace(code As XElement, expectedCode As XElement, data As NamespaceData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newNamespace = fileCodeModel.AddNamespace(data.Name, data.Position) Assert.NotNull(newNamespace) Assert.Equal(data.Name, newNamespace.Name) End Sub) End Function Protected Overrides Async Function TestAddStruct(code As XElement, expectedCode As XElement, data As StructData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newStruct = fileCodeModel.AddStruct(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access) Assert.NotNull(newStruct) Assert.Equal(data.Name, newStruct.Name) End Sub) End Function Protected Overrides Async Function TestAddVariable(code As XElement, expectedCode As XElement, data As VariableData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Assert.Throws(Of System.Runtime.InteropServices.COMException)( Sub() fileCodeModel.AddVariable(data.Name, data.Type, data.Position, data.Access) End Sub) End Sub) End Function Protected Overrides Async Function TestRemoveChild(code As XElement, expectedCode As XElement, element As Object) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) fileCodeModel.Remove(element) End Sub) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractFileCodeModelTests Inherits AbstractCodeModelObjectTests(Of EnvDTE80.FileCodeModel2) Protected Async Function TestOperation(code As XElement, expectedCode As XElement, operation As Action(Of EnvDTE80.FileCodeModel2)) As Task WpfTestRunner.RequireWpfFact($"Test calls {NameOf(Me.TestOperation)} which means we're creating new {NameOf(EnvDTE.CodeModel)} elements.") Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) operation(fileCodeModel) Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString() Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim()) End Using Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) fileCodeModel.BeginBatch() operation(fileCodeModel) fileCodeModel.EndBatch() Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString() Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim()) End Using End Function Protected Sub TestOperation(code As XElement, operation As Action(Of EnvDTE80.FileCodeModel2)) Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) operation(fileCodeModel) End Using Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) fileCodeModel.BeginBatch() operation(fileCodeModel) fileCodeModel.EndBatch() End Using End Sub Protected Overrides Sub TestChildren(code As XElement, ParamArray expectedChildren() As Action(Of Object)) TestOperation(code, Sub(fileCodeModel) Dim children = fileCodeModel.CodeElements Assert.Equal(expectedChildren.Length, children.Count) For i = 1 To children.Count expectedChildren(i - 1)(children.Item(i)) Next End Sub) End Sub Protected Overrides Async Function TestAddAttribute(code As XElement, expectedCode As XElement, data As AttributeData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newAttribute = fileCodeModel.AddAttribute(data.Name, data.Value, data.Position) Assert.NotNull(newAttribute) Assert.Equal(data.Name, newAttribute.Name) End Sub) End Function Protected Overrides Async Function TestAddClass(code As XElement, expectedCode As XElement, data As ClassData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newClass = fileCodeModel.AddClass(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access) Assert.NotNull(newClass) Assert.Equal(data.Name, newClass.Name) End Sub) End Function Protected Overrides Async Function TestAddDelegate(code As XElement, expectedCode As XElement, data As DelegateData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newDelegate = fileCodeModel.AddDelegate(data.Name, data.Type, data.Position, data.Access) Assert.NotNull(newDelegate) Assert.Equal(data.Name, newDelegate.Name) End Sub) End Function Protected Overrides Async Function TestAddEnum(code As XElement, expectedCode As XElement, data As EnumData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newEnum = fileCodeModel.AddEnum(data.Name, data.Position, data.Base, data.Access) Assert.NotNull(newEnum) Assert.Equal(data.Name, newEnum.Name) End Sub) End Function Protected Overrides Async Function TestAddFunction(code As XElement, expectedCode As XElement, data As FunctionData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Assert.Throws(Of System.Runtime.InteropServices.COMException)( Sub() fileCodeModel.AddFunction(data.Name, data.Kind, data.Type, data.Position, data.Access) End Sub) End Sub) End Function Protected Overrides Async Function TestAddImport(code As XElement, expectedCode As XElement, data As ImportData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newImport = fileCodeModel.AddImport(data.Namespace, data.Position, data.Alias) Assert.NotNull(newImport) Assert.Equal(data.Namespace, newImport.Namespace) If data.Alias IsNot Nothing Then Assert.Equal(data.Alias, newImport.Alias) End If End Sub) End Function Protected Overrides Async Function TestAddInterface(code As XElement, expectedCode As XElement, data As InterfaceData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newInterface = fileCodeModel.AddInterface(data.Name, data.Position, data.Bases, data.Access) Assert.NotNull(newInterface) Assert.Equal(data.Name, newInterface.Name) End Sub) End Function Protected Overrides Async Function TestAddNamespace(code As XElement, expectedCode As XElement, data As NamespaceData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newNamespace = fileCodeModel.AddNamespace(data.Name, data.Position) Assert.NotNull(newNamespace) Assert.Equal(data.Name, newNamespace.Name) End Sub) End Function Protected Overrides Async Function TestAddStruct(code As XElement, expectedCode As XElement, data As StructData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newStruct = fileCodeModel.AddStruct(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access) Assert.NotNull(newStruct) Assert.Equal(data.Name, newStruct.Name) End Sub) End Function Protected Overrides Async Function TestAddVariable(code As XElement, expectedCode As XElement, data As VariableData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Assert.Throws(Of System.Runtime.InteropServices.COMException)( Sub() fileCodeModel.AddVariable(data.Name, data.Type, data.Position, data.Access) End Sub) End Sub) End Function Protected Overrides Async Function TestRemoveChild(code As XElement, expectedCode As XElement, element As Object) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) fileCodeModel.Remove(element) End Sub) End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/CSharpTest/RawStringLiteral/RawStringLiteralCommandHandlerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.CSharp.RawStringLiteral; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RawStringLiteral { [UseExportProvider] public class RawStringLiteralCommandHandlerTests { internal sealed class RawStringLiteralTestState : AbstractCommandHandlerTestState { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeaturesWpf.AddParts( typeof(RawStringLiteralCommandHandler)); private readonly RawStringLiteralCommandHandler _commandHandler; public RawStringLiteralTestState(XElement workspaceElement) : base(workspaceElement, s_composition) { _commandHandler = (RawStringLiteralCommandHandler)GetExportedValues<ICommandHandler>(). Single(c => c is RawStringLiteralCommandHandler); } public static RawStringLiteralTestState CreateTestState(string markup) => new(GetWorkspaceXml(markup)); public static XElement GetWorkspaceXml(string markup) => XElement.Parse($@" <Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document>{markup}</Document> </Project> </Workspace>"); internal void AssertCodeIs(string expectedCode) { MarkupTestFile.GetPositionAndSpans(expectedCode, out var massaged, out int? caretPosition, out var spans); Assert.Equal(massaged, TextView.TextSnapshot.GetText()); Assert.Equal(caretPosition!.Value, TextView.Caret.Position.BufferPosition.Position); var virtualSpaces = spans.SingleOrDefault(kvp => kvp.Key.StartsWith("VirtualSpaces#")); if (virtualSpaces.Key != null) { var virtualOffset = int.Parse(virtualSpaces.Key.Substring("VirtualSpaces-".Length)); Assert.True(TextView.Caret.InVirtualSpace); Assert.Equal(virtualOffset, TextView.Caret.Position.VirtualBufferPosition.VirtualSpaces); } } public void SendTypeChar(char ch) => SendTypeChar(ch, _commandHandler.ExecuteCommand, () => EditorOperations.InsertText(ch.ToString())); public void SendReturn(bool handled) => SendReturn(_commandHandler.ExecuteCommand, () => { Assert.False(handled, "Return key should have been handled"); }); } #region enter tests [WpfFact] public void TestReturnInSixQuotes() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$"""""""); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = """""" $${|VirtualSpaces-4:|} """""""); } [WpfFact] public void TestReturnInSixQuotesWithSemicolonAfter() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$"""""";"); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = """""" $${|VirtualSpaces-4:|} """""";"); } [WpfFact] public void TestReturnInSixQuotesNotAtMiddle() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""""$$"""""); testState.SendReturn(handled: false); testState.AssertCodeIs( @"var v = """"""""$$"""""); } [WpfFact] public void TestReturnInSixQuotes_Interpolated() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $""""""$$"""""""); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = $"""""" $${|VirtualSpaces-4:|} """""""); } [WpfFact] public void TestReturnInSixQuotesMoreQuotesLaterOn() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$""""""; Console.WriteLine(""Goo"");"); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = """""" $${|VirtualSpaces-4:|} """"""; Console.WriteLine(""Goo"");"); } [WpfFact] public void TestReturnInSixQuotesAsArgument1() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = WriteLine(""""""$$"""""""); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = WriteLine("""""" $${|VirtualSpaces-4:|} """""""); } [WpfFact] public void TestReturnInSixQuotesAsArgument2() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = WriteLine(""""""$$"""""")"); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = WriteLine("""""" $${|VirtualSpaces-4:|} """""")"); } [WpfFact] public void TestReturnInSixQuotesAsArgument3() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = WriteLine(""""""$$"""""");"); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = WriteLine("""""" $${|VirtualSpaces-4:|} """""");"); } [WpfFact] public void TestReturnInSixQuotesAsArgument4() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = WriteLine( """"""$$"""""""); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = WriteLine( """""" $${|VirtualSpaces-4:|} """""""); } [WpfFact] public void TestReturnInSixQuotesAsArgument5() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = WriteLine( """"""$$"""""")"); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = WriteLine( """""" $${|VirtualSpaces-4:|} """""")"); } [WpfFact] public void TestReturnInSixQuotesAsArgument6() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = WriteLine( """"""$$"""""");"); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = WriteLine( """""" $${|VirtualSpaces-4:|} """""");"); } [WpfFact] public void TestReturnInSixQuotesWithSemicolonAfter_Interpolated() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $""""""$$"""""";"); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = $"""""" $${|VirtualSpaces-4:|} """""";"); } [WpfFact] public void TestReturnInSixQuotesNotAtMiddle_Interpolated() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $""""""""$$"""""); testState.SendReturn(handled: false); testState.AssertCodeIs( @"var v = $""""""""$$"""""); } [WpfFact] public void TestReturnEndOfFile() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$"); testState.SendReturn(handled: false); } [WpfFact] public void TestReturnInEmptyFile() { using var testState = RawStringLiteralTestState.CreateTestState( @"$$"); testState.SendReturn(handled: false); } #endregion #region generate initial empty raw string [WpfFact] public void TestGenerateAtEndOfFile() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"$$"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""$$"""""""); } [WpfFact] public void TestGenerateWithSemicolonAfter() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"$$;"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""$$"""""";"); } [WpfFact] public void TestGenerateWithInterpolatedString() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $""""$$"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = $""""""$$"""""""); } [WpfFact] public void TestNoGenerateWithVerbatimString() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = @""""$$"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = @""""""$$"); } [WpfFact] public void TestNoGenerateWithVerbatimInterpolatedString1() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = @$""""$$"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = @$""""""$$"); } [WpfFact] public void TestNoGenerateWithVerbatimInterpolatedString2() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $@""""$$"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = $@""""""$$"); } #endregion #region grow empty raw string [WpfFact] public void TestDoNotGrowEmptyInsideSimpleString() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = ""$$"""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"$$"""); } [WpfFact] public void TestDoNotGrowEmptyInsideFourQuotes() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"$$"""""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""$$"""""); } [WpfFact] public void TestDoGrowEmptyInsideSixQuotesInMiddle() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$"""""""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""""$$"""""""""); } [WpfFact] public void TestDoGrowEmptyInsideSixQuotesInInterpolatedRaw() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $""""""$$"""""""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = $""""""""$$"""""""""); } [WpfFact] public void TestDoNotGrowEmptyInsideSixQuotesWhenNotInMiddle1() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $""""$$"""""""""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = $""""""$$"""""""""); } #endregion #region grow delimiters [WpfFact] public void TestGrowDelimetersWhenEndExists_SingleLine() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$ """""""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""""$$ """""""""); } [WpfFact] public void TestGrowDelimetersWhenEndExists_MultiLine() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$ """""""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""""$$ """""""""); } [WpfFact] public void TestGrowDelimetersWhenEndExists_Interpolated() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $""""""$$ """""""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = $""""""""$$ """""""""); } [WpfFact] public void TestDoNotGrowDelimetersWhenEndNotThere() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""""$$"); } [WpfFact] public void TestDoNotGrowDelimetersWhenEndTooShort() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$ """""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""""$$ """""); } #endregion [WpfFact] public void TestTypeQuoteEmptyFile() { using var testState = RawStringLiteralTestState.CreateTestState( @"$$"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"""$$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.CSharp.RawStringLiteral; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RawStringLiteral { [UseExportProvider] public class RawStringLiteralCommandHandlerTests { internal sealed class RawStringLiteralTestState : AbstractCommandHandlerTestState { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeaturesWpf.AddParts( typeof(RawStringLiteralCommandHandler)); private readonly RawStringLiteralCommandHandler _commandHandler; public RawStringLiteralTestState(XElement workspaceElement) : base(workspaceElement, s_composition) { _commandHandler = (RawStringLiteralCommandHandler)GetExportedValues<ICommandHandler>(). Single(c => c is RawStringLiteralCommandHandler); } public static RawStringLiteralTestState CreateTestState(string markup) => new(GetWorkspaceXml(markup)); public static XElement GetWorkspaceXml(string markup) => XElement.Parse($@" <Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document>{markup}</Document> </Project> </Workspace>"); internal void AssertCodeIs(string expectedCode) { MarkupTestFile.GetPositionAndSpans(expectedCode, out var massaged, out int? caretPosition, out var spans); Assert.Equal(massaged, TextView.TextSnapshot.GetText()); Assert.Equal(caretPosition!.Value, TextView.Caret.Position.BufferPosition.Position); var virtualSpaces = spans.SingleOrDefault(kvp => kvp.Key.StartsWith("VirtualSpaces#")); if (virtualSpaces.Key != null) { var virtualOffset = int.Parse(virtualSpaces.Key.Substring("VirtualSpaces-".Length)); Assert.True(TextView.Caret.InVirtualSpace); Assert.Equal(virtualOffset, TextView.Caret.Position.VirtualBufferPosition.VirtualSpaces); } } public void SendTypeChar(char ch) => SendTypeChar(ch, _commandHandler.ExecuteCommand, () => EditorOperations.InsertText(ch.ToString())); public void SendReturn(bool handled) => SendReturn(_commandHandler.ExecuteCommand, () => { Assert.False(handled, "Return key should have been handled"); }); } #region enter tests [WpfFact] public void TestReturnInSixQuotes() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$"""""""); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = """""" $${|VirtualSpaces-4:|} """""""); } [WpfFact] public void TestReturnInSixQuotesWithSemicolonAfter() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$"""""";"); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = """""" $${|VirtualSpaces-4:|} """""";"); } [WpfFact] public void TestReturnInSixQuotesNotAtMiddle() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""""$$"""""); testState.SendReturn(handled: false); testState.AssertCodeIs( @"var v = """"""""$$"""""); } [WpfFact] public void TestReturnInSixQuotes_Interpolated() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $""""""$$"""""""); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = $"""""" $${|VirtualSpaces-4:|} """""""); } [WpfFact] public void TestReturnInSixQuotesMoreQuotesLaterOn() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$""""""; Console.WriteLine(""Goo"");"); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = """""" $${|VirtualSpaces-4:|} """"""; Console.WriteLine(""Goo"");"); } [WpfFact] public void TestReturnInSixQuotesAsArgument1() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = WriteLine(""""""$$"""""""); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = WriteLine("""""" $${|VirtualSpaces-4:|} """""""); } [WpfFact] public void TestReturnInSixQuotesAsArgument2() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = WriteLine(""""""$$"""""")"); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = WriteLine("""""" $${|VirtualSpaces-4:|} """""")"); } [WpfFact] public void TestReturnInSixQuotesAsArgument3() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = WriteLine(""""""$$"""""");"); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = WriteLine("""""" $${|VirtualSpaces-4:|} """""");"); } [WpfFact] public void TestReturnInSixQuotesAsArgument4() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = WriteLine( """"""$$"""""""); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = WriteLine( """""" $${|VirtualSpaces-4:|} """""""); } [WpfFact] public void TestReturnInSixQuotesAsArgument5() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = WriteLine( """"""$$"""""")"); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = WriteLine( """""" $${|VirtualSpaces-4:|} """""")"); } [WpfFact] public void TestReturnInSixQuotesAsArgument6() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = WriteLine( """"""$$"""""");"); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = WriteLine( """""" $${|VirtualSpaces-4:|} """""");"); } [WpfFact] public void TestReturnInSixQuotesWithSemicolonAfter_Interpolated() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $""""""$$"""""";"); testState.SendReturn(handled: true); testState.AssertCodeIs( @"var v = $"""""" $${|VirtualSpaces-4:|} """""";"); } [WpfFact] public void TestReturnInSixQuotesNotAtMiddle_Interpolated() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $""""""""$$"""""); testState.SendReturn(handled: false); testState.AssertCodeIs( @"var v = $""""""""$$"""""); } [WpfFact] public void TestReturnEndOfFile() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$"); testState.SendReturn(handled: false); } [WpfFact] public void TestReturnInEmptyFile() { using var testState = RawStringLiteralTestState.CreateTestState( @"$$"); testState.SendReturn(handled: false); } #endregion #region generate initial empty raw string [WpfFact] public void TestGenerateAtEndOfFile() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"$$"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""$$"""""""); } [WpfFact] public void TestGenerateWithSemicolonAfter() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"$$;"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""$$"""""";"); } [WpfFact] public void TestGenerateWithInterpolatedString() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $""""$$"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = $""""""$$"""""""); } [WpfFact] public void TestNoGenerateWithVerbatimString() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = @""""$$"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = @""""""$$"); } [WpfFact] public void TestNoGenerateWithVerbatimInterpolatedString1() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = @$""""$$"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = @$""""""$$"); } [WpfFact] public void TestNoGenerateWithVerbatimInterpolatedString2() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $@""""$$"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = $@""""""$$"); } #endregion #region grow empty raw string [WpfFact] public void TestDoNotGrowEmptyInsideSimpleString() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = ""$$"""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"$$"""); } [WpfFact] public void TestDoNotGrowEmptyInsideFourQuotes() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"$$"""""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""$$"""""); } [WpfFact] public void TestDoGrowEmptyInsideSixQuotesInMiddle() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$"""""""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""""$$"""""""""); } [WpfFact] public void TestDoGrowEmptyInsideSixQuotesInInterpolatedRaw() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $""""""$$"""""""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = $""""""""$$"""""""""); } [WpfFact] public void TestDoNotGrowEmptyInsideSixQuotesWhenNotInMiddle1() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $""""$$"""""""""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = $""""""$$"""""""""); } #endregion #region grow delimiters [WpfFact] public void TestGrowDelimetersWhenEndExists_SingleLine() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$ """""""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""""$$ """""""""); } [WpfFact] public void TestGrowDelimetersWhenEndExists_MultiLine() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$ """""""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""""$$ """""""""); } [WpfFact] public void TestGrowDelimetersWhenEndExists_Interpolated() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = $""""""$$ """""""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = $""""""""$$ """""""""); } [WpfFact] public void TestDoNotGrowDelimetersWhenEndNotThere() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""""$$"); } [WpfFact] public void TestDoNotGrowDelimetersWhenEndTooShort() { using var testState = RawStringLiteralTestState.CreateTestState( @"var v = """"""$$ """""); testState.SendTypeChar('"'); testState.AssertCodeIs( @"var v = """"""""$$ """""); } #endregion [WpfFact] public void TestTypeQuoteEmptyFile() { using var testState = RawStringLiteralTestState.CreateTestState( @"$$"); testState.SendTypeChar('"'); testState.AssertCodeIs( @"""$$"); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Test/Emit/CodeGen/PatternTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class PatternTests : EmitMetadataTestBase { #region Miscellaneous [Fact, WorkItem(48493, "https://github.com/dotnet/roslyn/issues/48493")] public void Repro_48493() { var source = @" using System; using System.Linq; namespace Sample { internal class Row { public string Message { get; set; } = """"; } internal class Program { private static void Main() { Console.WriteLine(ProcessRow(new Row())); } private static string ProcessRow(Row row) { if (row == null) throw new ArgumentNullException(nameof(row)); return row switch { { Message: ""stringA"" } => ""stringB"", var r when new[] { ""stringC"", ""stringD"" }.Any(x => r.Message.Contains(x)) => ""stringE"", { Message: ""stringF"" } => ""stringG"", _ => ""stringH"", }; } } }"; CompileAndVerify(source, expectedOutput: "stringH"); } [Fact, WorkItem(48493, "https://github.com/dotnet/roslyn/issues/48493")] public void Repro_48493_Simple() { var source = @" using System; internal class Widget { public bool IsGood { get; set; } } internal class Program { private static bool M0(Func<bool> fn) => fn(); private static void Main() { Console.Write(new Widget() switch { { IsGood: true } => 1, _ when M0(() => true) => 2, { } => 3, }); } }"; CompileAndVerify(source, expectedOutput: @"2"); } [Fact, WorkItem(18811, "https://github.com/dotnet/roslyn/issues/18811")] public void MissingNullable_01() { var source = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } static class C { public static bool M() => ((object)123) is int i; } "; var compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseDll); compilation.GetDiagnostics().Verify(); compilation.GetEmitDiagnostics().Verify( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) ); } [Fact, WorkItem(18811, "https://github.com/dotnet/roslyn/issues/18811")] public void MissingNullable_02() { var source = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct Nullable<T> where T : struct { } } static class C { public static bool M() => ((object)123) is int i; } "; var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll); compilation.GetDiagnostics().Verify(); compilation.GetEmitDiagnostics().Verify( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion) ); } [Fact] public void MissingNullable_03() { var source = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct Nullable<T> where T : struct { } } static class C { static void M1(int? x) { switch (x) { case int i: break; } } static bool M2(int? x) => x is int i; } "; var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll); compilation.GetDiagnostics().Verify(); compilation.GetEmitDiagnostics().Verify( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // case int i: break; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(14, 18), // (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // case int i: break; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(14, 18), // (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.get_Value' // case int i: break; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_Value").WithLocation(14, 18), // (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // static bool M2(int? x) => x is int i; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(17, 36), // (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // static bool M2(int? x) => x is int i; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(17, 36), // (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_Value' // static bool M2(int? x) => x is int i; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_Value").WithLocation(17, 36) ); } [Fact] public void MissingNullable_04() { var source = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct Nullable<T> where T : struct { public T GetValueOrDefault() => default(T); } } static class C { static void M1(int? x) { switch (x) { case int i: break; } } static bool M2(int? x) => x is int i; } "; var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll); compilation.GetDiagnostics().Verify(); compilation.GetEmitDiagnostics().Verify( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // case int i: break; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(14, 18), // (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // static bool M2(int? x) => x is int i; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(17, 36) ); } [Fact, WorkItem(17266, "https://github.com/dotnet/roslyn/issues/17266")] public void DoubleEvaluation01() { var source = @"using System; public class C { public static void Main() { if (TryGet() is int index) { Console.WriteLine(index); } } public static int? TryGet() { Console.WriteLine(""eval""); return null; } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"eval"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.Main", @"{ // Code size 42 (0x2a) .maxstack 1 .locals init (int V_0, //index bool V_1, int? V_2) IL_0000: nop IL_0001: call ""int? C.TryGet()"" IL_0006: stloc.2 IL_0007: ldloca.s V_2 IL_0009: call ""bool int?.HasValue.get"" IL_000e: brfalse.s IL_001b IL_0010: ldloca.s V_2 IL_0012: call ""int int?.GetValueOrDefault()"" IL_0017: stloc.0 IL_0018: ldc.i4.1 IL_0019: br.s IL_001c IL_001b: ldc.i4.0 IL_001c: stloc.1 IL_001d: ldloc.1 IL_001e: brfalse.s IL_0029 IL_0020: nop IL_0021: ldloc.0 IL_0022: call ""void System.Console.WriteLine(int)"" IL_0027: nop IL_0028: nop IL_0029: ret }"); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.Main", @"{ // Code size 30 (0x1e) .maxstack 1 .locals init (int V_0, //index int? V_1) IL_0000: call ""int? C.TryGet()"" IL_0005: stloc.1 IL_0006: ldloca.s V_1 IL_0008: call ""bool int?.HasValue.get"" IL_000d: brfalse.s IL_001d IL_000f: ldloca.s V_1 IL_0011: call ""int int?.GetValueOrDefault()"" IL_0016: stloc.0 IL_0017: ldloc.0 IL_0018: call ""void System.Console.WriteLine(int)"" IL_001d: ret }"); } [Fact, WorkItem(19122, "https://github.com/dotnet/roslyn/issues/19122")] public void PatternCrash_01() { var source = @"using System; using System.Collections.Generic; using System.Linq; public class Class2 : IDisposable { public Class2(bool parameter = false) { } public void Dispose() { } } class X<T> { IdentityAccessor<T> idAccessor = new IdentityAccessor<T>(); void Y<U>() where U : T { // BUG: The following line is the problem if (GetT().FirstOrDefault(p => idAccessor.GetId(p) == Guid.Empty) is U u) { } } IEnumerable<T> GetT() { yield return default(T); } } class IdentityAccessor<T> { public Guid GetId(T t) { return Guid.Empty; } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("X<T>.Y<U>", @"{ // Code size 61 (0x3d) .maxstack 3 .locals init (U V_0, //u bool V_1, T V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""System.Collections.Generic.IEnumerable<T> X<T>.GetT()"" IL_0007: ldarg.0 IL_0008: ldftn ""bool X<T>.<Y>b__1_0<U>(T)"" IL_000e: newobj ""System.Func<T, bool>..ctor(object, System.IntPtr)"" IL_0013: call ""T System.Linq.Enumerable.FirstOrDefault<T>(System.Collections.Generic.IEnumerable<T>, System.Func<T, bool>)"" IL_0018: stloc.2 IL_0019: ldloc.2 IL_001a: box ""T"" IL_001f: isinst ""U"" IL_0024: brfalse.s IL_0035 IL_0026: ldloc.2 IL_0027: box ""T"" IL_002c: unbox.any ""U"" IL_0031: stloc.0 IL_0032: ldc.i4.1 IL_0033: br.s IL_0036 IL_0035: ldc.i4.0 IL_0036: stloc.1 IL_0037: ldloc.1 IL_0038: brfalse.s IL_003c IL_003a: nop IL_003b: nop IL_003c: ret }"); } [Fact, WorkItem(24522, "https://github.com/dotnet/roslyn/issues/24522")] public void IgnoreDeclaredConversion_01() { var source = @"class Base<T> { public static implicit operator Derived(Base<T> obj) { return new Derived(); } } class Derived : Base<object> { } class Program { static void Main(string[] args) { Base<object> x = new Derived(); System.Console.WriteLine(x is Derived); System.Console.WriteLine(x is Derived y); switch (x) { case Derived z: System.Console.WriteLine(true); break; } System.Console.WriteLine(null != (x as Derived)); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"True True True True"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("Program.Main", @"{ // Code size 84 (0x54) .maxstack 2 .locals init (Base<object> V_0, //x Derived V_1, //y Derived V_2, //z Base<object> V_3, Base<object> V_4) IL_0000: nop IL_0001: newobj ""Derived..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: isinst ""Derived"" IL_000d: ldnull IL_000e: cgt.un IL_0010: call ""void System.Console.WriteLine(bool)"" IL_0015: nop IL_0016: ldloc.0 IL_0017: isinst ""Derived"" IL_001c: stloc.1 IL_001d: ldloc.1 IL_001e: ldnull IL_001f: cgt.un IL_0021: call ""void System.Console.WriteLine(bool)"" IL_0026: nop IL_0027: ldloc.0 IL_0028: stloc.s V_4 IL_002a: ldloc.s V_4 IL_002c: stloc.3 IL_002d: ldloc.3 IL_002e: isinst ""Derived"" IL_0033: stloc.2 IL_0034: ldloc.2 IL_0035: brtrue.s IL_0039 IL_0037: br.s IL_0044 IL_0039: br.s IL_003b IL_003b: ldc.i4.1 IL_003c: call ""void System.Console.WriteLine(bool)"" IL_0041: nop IL_0042: br.s IL_0044 IL_0044: ldloc.0 IL_0045: isinst ""Derived"" IL_004a: ldnull IL_004b: cgt.un IL_004d: call ""void System.Console.WriteLine(bool)"" IL_0052: nop IL_0053: ret }"); } [Fact] public void DoublePattern01() { var source = @"using System; class Program { static bool P1(double d) => d is double.NaN; static bool P2(float f) => f is float.NaN; static bool P3(double d) => d is 3.14d; static bool P4(float f) => f is 3.14f; static bool P5(object o) { switch (o) { case double.NaN: return true; case float.NaN: return true; case 3.14d: return true; case 3.14f: return true; default: return false; } } public static void Main(string[] args) { Console.Write(P1(double.NaN)); Console.Write(P1(1.0)); Console.Write(P2(float.NaN)); Console.Write(P2(1.0f)); Console.Write(P3(3.14)); Console.Write(P3(double.NaN)); Console.Write(P4(3.14f)); Console.Write(P4(float.NaN)); Console.Write(P5(double.NaN)); Console.Write(P5(0.0d)); Console.Write(P5(float.NaN)); Console.Write(P5(0.0f)); Console.Write(P5(3.14d)); Console.Write(P5(125)); Console.Write(P5(3.14f)); Console.Write(P5(1.0f)); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"TrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalse"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("Program.P1", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""bool double.IsNaN(double)"" IL_0006: ret }"); compVerifier.VerifyIL("Program.P2", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""bool float.IsNaN(float)"" IL_0006: ret }"); compVerifier.VerifyIL("Program.P3", @"{ // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.r8 3.14 IL_000a: ceq IL_000c: ret }"); compVerifier.VerifyIL("Program.P4", @"{ // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.r4 3.14 IL_0006: ceq IL_0008: ret }"); compVerifier.VerifyIL("Program.P5", @"{ // Code size 103 (0x67) .maxstack 2 .locals init (object V_0, double V_1, float V_2, object V_3, bool V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.0 IL_0005: ldloc.0 IL_0006: isinst ""double"" IL_000b: brfalse.s IL_002a IL_000d: ldloc.0 IL_000e: unbox.any ""double"" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: call ""bool double.IsNaN(double)"" IL_001a: brtrue.s IL_004b IL_001c: ldloc.1 IL_001d: ldc.r8 3.14 IL_0026: beq.s IL_0055 IL_0028: br.s IL_005f IL_002a: ldloc.0 IL_002b: isinst ""float"" IL_0030: brfalse.s IL_005f IL_0032: ldloc.0 IL_0033: unbox.any ""float"" IL_0038: stloc.2 IL_0039: ldloc.2 IL_003a: call ""bool float.IsNaN(float)"" IL_003f: brtrue.s IL_0050 IL_0041: ldloc.2 IL_0042: ldc.r4 3.14 IL_0047: beq.s IL_005a IL_0049: br.s IL_005f IL_004b: ldc.i4.1 IL_004c: stloc.s V_4 IL_004e: br.s IL_0064 IL_0050: ldc.i4.1 IL_0051: stloc.s V_4 IL_0053: br.s IL_0064 IL_0055: ldc.i4.1 IL_0056: stloc.s V_4 IL_0058: br.s IL_0064 IL_005a: ldc.i4.1 IL_005b: stloc.s V_4 IL_005d: br.s IL_0064 IL_005f: ldc.i4.0 IL_0060: stloc.s V_4 IL_0062: br.s IL_0064 IL_0064: ldloc.s V_4 IL_0066: ret }"); } [Fact] public void DecimalEquality() { // demonstrate that pattern-matching against a decimal constant is // at least as efficient as simply using == var source = @"using System; public class C { public static void Main() { Console.Write(M1(1.0m)); Console.Write(M2(1.0m)); Console.Write(M1(2.0m)); Console.Write(M2(2.0m)); } static int M1(decimal d) { if (M(d) is 1.0m) return 1; return 0; } static int M2(decimal d) { if (M(d) == 1.0m) return 1; return 0; } public static decimal M(decimal d) { return d; } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"1100"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @"{ // Code size 37 (0x25) .maxstack 6 .locals init (bool V_0, int V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""decimal C.M(decimal)"" IL_0007: ldc.i4.s 10 IL_0009: ldc.i4.0 IL_000a: ldc.i4.0 IL_000b: ldc.i4.0 IL_000c: ldc.i4.1 IL_000d: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0012: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0017: stloc.0 IL_0018: ldloc.0 IL_0019: brfalse.s IL_001f IL_001b: ldc.i4.1 IL_001c: stloc.1 IL_001d: br.s IL_0023 IL_001f: ldc.i4.0 IL_0020: stloc.1 IL_0021: br.s IL_0023 IL_0023: ldloc.1 IL_0024: ret }"); compVerifier.VerifyIL("C.M2", @"{ // Code size 37 (0x25) .maxstack 6 .locals init (bool V_0, int V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""decimal C.M(decimal)"" IL_0007: ldc.i4.s 10 IL_0009: ldc.i4.0 IL_000a: ldc.i4.0 IL_000b: ldc.i4.0 IL_000c: ldc.i4.1 IL_000d: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0012: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0017: stloc.0 IL_0018: ldloc.0 IL_0019: brfalse.s IL_001f IL_001b: ldc.i4.1 IL_001c: stloc.1 IL_001d: br.s IL_0023 IL_001f: ldc.i4.0 IL_0020: stloc.1 IL_0021: br.s IL_0023 IL_0023: ldloc.1 IL_0024: ret }"); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @"{ // Code size 28 (0x1c) .maxstack 6 IL_0000: ldarg.0 IL_0001: call ""decimal C.M(decimal)"" IL_0006: ldc.i4.s 10 IL_0008: ldc.i4.0 IL_0009: ldc.i4.0 IL_000a: ldc.i4.0 IL_000b: ldc.i4.1 IL_000c: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0011: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0016: brfalse.s IL_001a IL_0018: ldc.i4.1 IL_0019: ret IL_001a: ldc.i4.0 IL_001b: ret }"); compVerifier.VerifyIL("C.M2", @"{ // Code size 28 (0x1c) .maxstack 6 IL_0000: ldarg.0 IL_0001: call ""decimal C.M(decimal)"" IL_0006: ldc.i4.s 10 IL_0008: ldc.i4.0 IL_0009: ldc.i4.0 IL_000a: ldc.i4.0 IL_000b: ldc.i4.1 IL_000c: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0011: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0016: brfalse.s IL_001a IL_0018: ldc.i4.1 IL_0019: ret IL_001a: ldc.i4.0 IL_001b: ret }"); } [Fact, WorkItem(16878, "https://github.com/dotnet/roslyn/issues/16878")] public void RedundantNullCheck() { var source = @"public class C { static int M1(bool? b1, bool b2) { switch (b1) { case null: return 1; case var _ when b2: return 2; case true: return 3; case false: return 4; } } static int M2(object o, bool b) { switch (o) { case string a when b: return 1; case string a: return 2; } return 3; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1", @"{ // Code size 35 (0x23) .maxstack 1 .locals init (bool? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool bool?.HasValue.get"" IL_0009: brfalse.s IL_0018 IL_000b: br.s IL_001a IL_000d: ldloca.s V_0 IL_000f: call ""bool bool?.GetValueOrDefault()"" IL_0014: brtrue.s IL_001f IL_0016: br.s IL_0021 IL_0018: ldc.i4.1 IL_0019: ret IL_001a: ldarg.1 IL_001b: brfalse.s IL_000d IL_001d: ldc.i4.2 IL_001e: ret IL_001f: ldc.i4.3 IL_0020: ret IL_0021: ldc.i4.4 IL_0022: ret }"); compVerifier.VerifyIL("C.M2", @"{ // Code size 19 (0x13) .maxstack 1 .locals init (string V_0) //a IL_0000: ldarg.0 IL_0001: isinst ""string"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0011 IL_000a: ldarg.1 IL_000b: brfalse.s IL_000f IL_000d: ldc.i4.1 IL_000e: ret IL_000f: ldc.i4.2 IL_0010: ret IL_0011: ldc.i4.3 IL_0012: ret }"); } [Fact, WorkItem(12813, "https://github.com/dotnet/roslyn/issues/12813")] public void NoBoxingOnIntegerConstantPattern() { var source = @"public class C { static bool M1(int x) { return x is 42; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1", @"{ // Code size 6 (0x6) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: ceq IL_0005: ret }"); } [Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")] public void RefParameter_StoreToTemp() { var source = @"public class C { static bool M1(ref object x) { return x is 42; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1", @"{ // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: ldind.ref IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: isinst ""int"" IL_0009: brfalse.s IL_0016 IL_000b: ldloc.0 IL_000c: unbox.any ""int"" IL_0011: ldc.i4.s 42 IL_0013: ceq IL_0015: ret IL_0016: ldc.i4.0 IL_0017: ret }"); } [Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")] public void RefLocal_StoreToTemp() { var source = @"public class C { static bool M1(bool b, ref object x, ref object y) { ref object z = ref b ? ref x : ref y; return z is 42; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1", @"{ // Code size 30 (0x1e) .maxstack 2 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_0006 IL_0003: ldarg.2 IL_0004: br.s IL_0007 IL_0006: ldarg.1 IL_0007: ldind.ref IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: isinst ""int"" IL_000f: brfalse.s IL_001c IL_0011: ldloc.0 IL_0012: unbox.any ""int"" IL_0017: ldc.i4.s 42 IL_0019: ceq IL_001b: ret IL_001c: ldc.i4.0 IL_001d: ret }"); } [Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")] public void InParameter_StoreToTemp() { var source = @"public class C { static bool M1(in object x) { return x is 42; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1", @"{ // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: ldind.ref IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: isinst ""int"" IL_0009: brfalse.s IL_0016 IL_000b: ldloc.0 IL_000c: unbox.any ""int"" IL_0011: ldc.i4.s 42 IL_0013: ceq IL_0015: ret IL_0016: ldc.i4.0 IL_0017: ret }"); } [Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")] public void RefReadonlyLocal_StoreToTemp() { var source = @"public class C { static bool M1(bool b, in object x, in object y) { ref readonly object z = ref b ? ref x : ref y; return z is 42; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1", @"{ // Code size 30 (0x1e) .maxstack 2 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_0006 IL_0003: ldarg.2 IL_0004: br.s IL_0007 IL_0006: ldarg.1 IL_0007: ldind.ref IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: isinst ""int"" IL_000f: brfalse.s IL_001c IL_0011: ldloc.0 IL_0012: unbox.any ""int"" IL_0017: ldc.i4.s 42 IL_0019: ceq IL_001b: ret IL_001c: ldc.i4.0 IL_001d: ret }"); } [Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")] public void OutParameter_StoreToTemp() { var source = @"public class C { static bool M1(out object x) { x = null; return x is 42; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1", @"{ // Code size 27 (0x1b) .maxstack 2 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: ldnull IL_0002: stind.ref IL_0003: ldarg.0 IL_0004: ldind.ref IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: isinst ""int"" IL_000c: brfalse.s IL_0019 IL_000e: ldloc.0 IL_000f: unbox.any ""int"" IL_0014: ldc.i4.s 42 IL_0016: ceq IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret }"); } [Fact, WorkItem(22654, "https://github.com/dotnet/roslyn/issues/22654")] public void NoRedundantTypeCheck() { var source = @"using System; public class C { public void SwitchBasedPatternMatching(object o) { switch (o) { case int n when n == 1: Console.WriteLine(""1""); break; case string s: Console.WriteLine(""s""); break; case int n when n == 2: Console.WriteLine(""2""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.SwitchBasedPatternMatching", @"{ // Code size 69 (0x45) .maxstack 2 .locals init (int V_0, //n object V_1) IL_0000: ldarg.1 IL_0001: stloc.1 IL_0002: ldloc.1 IL_0003: isinst ""int"" IL_0008: brfalse.s IL_0013 IL_000a: ldloc.1 IL_000b: unbox.any ""int"" IL_0010: stloc.0 IL_0011: br.s IL_001c IL_0013: ldloc.1 IL_0014: isinst ""string"" IL_0019: brtrue.s IL_002b IL_001b: ret IL_001c: ldloc.0 IL_001d: ldc.i4.1 IL_001e: bne.un.s IL_0036 IL_0020: ldstr ""1"" IL_0025: call ""void System.Console.WriteLine(string)"" IL_002a: ret IL_002b: ldstr ""s"" IL_0030: call ""void System.Console.WriteLine(string)"" IL_0035: ret IL_0036: ldloc.0 IL_0037: ldc.i4.2 IL_0038: bne.un.s IL_0044 IL_003a: ldstr ""2"" IL_003f: call ""void System.Console.WriteLine(string)"" IL_0044: ret }"); } [Fact, WorkItem(15437, "https://github.com/dotnet/roslyn/issues/15437")] public void IsTypeDiscard() { var source = @"public class C { public bool IsString(object o) { return o is string _; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.IsString", @"{ // Code size 10 (0xa) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""string"" IL_0006: ldnull IL_0007: cgt.un IL_0009: ret }"); } [Fact, WorkItem(19150, "https://github.com/dotnet/roslyn/issues/19150")] public void RedundantHasValue() { var source = @"using System; public class C { public static void M(int? x) { switch (x) { case int i: Console.Write(i); break; case null: Console.Write(""null""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 33 (0x21) .maxstack 1 IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brfalse.s IL_0016 IL_0009: ldarga.s V_0 IL_000b: call ""int int?.GetValueOrDefault()"" IL_0010: call ""void System.Console.Write(int)"" IL_0015: ret IL_0016: ldstr ""null"" IL_001b: call ""void System.Console.Write(string)"" IL_0020: ret }"); } [Fact, WorkItem(19153, "https://github.com/dotnet/roslyn/issues/19153")] public void RedundantBox() { var source = @"using System; public class C { public static void M<T, U>(U x) where T : U { // when T is not known to be a reference type, there is an unboxing conversion from // a type parameter U to T, provided T depends on U. switch (x) { case T i: Console.Write(i); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M<T, U>(U)", @"{ // Code size 35 (0x23) .maxstack 1 IL_0000: ldarg.0 IL_0001: box ""U"" IL_0006: isinst ""T"" IL_000b: brfalse.s IL_0022 IL_000d: ldarg.0 IL_000e: box ""U"" IL_0013: unbox.any ""T"" IL_0018: box ""T"" IL_001d: call ""void System.Console.Write(object)"" IL_0022: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead01() { var source = @"using System; public class Person { public string Name { get; set; } } public class C { public void M(Person p) { switch (p) { case { Name: ""Bill"" }: Console.WriteLine(""Hey Bill!""); break; case { Name: ""Bob"" }: Console.WriteLine(""Hey Bob!""); break; case { Name: var name }: Console.WriteLine($""Hello {name}!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 82 (0x52) .maxstack 3 .locals init (string V_0) //name IL_0000: ldarg.1 IL_0001: brfalse.s IL_0051 IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldstr ""Bill"" IL_0010: call ""bool string.op_Equality(string, string)"" IL_0015: brtrue.s IL_0026 IL_0017: ldloc.0 IL_0018: ldstr ""Bob"" IL_001d: call ""bool string.op_Equality(string, string)"" IL_0022: brtrue.s IL_0031 IL_0024: br.s IL_003c IL_0026: ldstr ""Hey Bill!"" IL_002b: call ""void System.Console.WriteLine(string)"" IL_0030: ret IL_0031: ldstr ""Hey Bob!"" IL_0036: call ""void System.Console.WriteLine(string)"" IL_003b: ret IL_003c: ldstr ""Hello "" IL_0041: ldloc.0 IL_0042: ldstr ""!"" IL_0047: call ""string string.Concat(string, string, string)"" IL_004c: call ""void System.Console.WriteLine(string)"" IL_0051: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead02() { var source = @"using System; public class Person { public string Name { get; set; } public int Age; } public class C { public void M(Person p) { switch (p) { case Person { Name: var name, Age: 0}: Console.WriteLine($""Hello baby { name }!""); break; case Person { Name: var name }: Console.WriteLine($""Hello { name }!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 64 (0x40) .maxstack 3 .locals init (string V_0, //name string V_1) //name IL_0000: ldarg.1 IL_0001: brfalse.s IL_003f IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: ldfld ""int Person.Age"" IL_0010: brtrue.s IL_0028 IL_0012: ldstr ""Hello baby "" IL_0017: ldloc.0 IL_0018: ldstr ""!"" IL_001d: call ""string string.Concat(string, string, string)"" IL_0022: call ""void System.Console.WriteLine(string)"" IL_0027: ret IL_0028: ldloc.0 IL_0029: stloc.1 IL_002a: ldstr ""Hello "" IL_002f: ldloc.1 IL_0030: ldstr ""!"" IL_0035: call ""string string.Concat(string, string, string)"" IL_003a: call ""void System.Console.WriteLine(string)"" IL_003f: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead03() { var source = @"using System; public class Person { public string Name { get; set; } } public class Student : Person { } public class C { public void M(Person p) { switch (p) { case { Name: ""Bill"" }: Console.WriteLine(""Hey Bill!""); break; case Student { Name: var name }: Console.WriteLine($""Hello student { name}!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 65 (0x41) .maxstack 3 .locals init (string V_0) //name IL_0000: ldarg.1 IL_0001: brfalse.s IL_0040 IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldstr ""Bill"" IL_0010: call ""bool string.op_Equality(string, string)"" IL_0015: brtrue.s IL_0020 IL_0017: ldarg.1 IL_0018: isinst ""Student"" IL_001d: brtrue.s IL_002b IL_001f: ret IL_0020: ldstr ""Hey Bill!"" IL_0025: call ""void System.Console.WriteLine(string)"" IL_002a: ret IL_002b: ldstr ""Hello student "" IL_0030: ldloc.0 IL_0031: ldstr ""!"" IL_0036: call ""string string.Concat(string, string, string)"" IL_003b: call ""void System.Console.WriteLine(string)"" IL_0040: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead04() { // Cannot combine the evaluations of name here, since we first check if p is Teacher, // and only if that fails check if p is null. // Combining the evaluations would mean first checking if p is null, then evaluating name, then checking if p is Teacher. // This would not necessarily be more performant. var source = @"using System; public class Person { public string Name { get; set; } } public class Teacher : Person { } public class C { public void M(Person p) { switch (p) { case Teacher { Name: var name }: Console.WriteLine($""Hello teacher { name}!""); break; case Person { Name: var name }: Console.WriteLine($""Hello { name}!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 75 (0x4b) .maxstack 3 .locals init (string V_0, //name string V_1) //name IL_0000: ldarg.1 IL_0001: isinst ""Teacher"" IL_0006: brfalse.s IL_0011 IL_0008: ldarg.1 IL_0009: callvirt ""string Person.Name.get"" IL_000e: stloc.0 IL_000f: br.s IL_001d IL_0011: ldarg.1 IL_0012: brfalse.s IL_004a IL_0014: ldarg.1 IL_0015: callvirt ""string Person.Name.get"" IL_001a: stloc.0 IL_001b: br.s IL_0033 IL_001d: ldstr ""Hello teacher "" IL_0022: ldloc.0 IL_0023: ldstr ""!"" IL_0028: call ""string string.Concat(string, string, string)"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ret IL_0033: ldloc.0 IL_0034: stloc.1 IL_0035: ldstr ""Hello "" IL_003a: ldloc.1 IL_003b: ldstr ""!"" IL_0040: call ""string string.Concat(string, string, string)"" IL_0045: call ""void System.Console.WriteLine(string)"" IL_004a: ret } "); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead05() { // Cannot combine the evaluations of name here, since we first check if p is Teacher, // and only if that fails check if p is Student. // Combining the evaluations would mean first checking if p is null, // then evaluating name, // then checking if p is Teacher, // then checking if p is Student. // This would not necessarily be more performant. var source = @"using System; public class Person { public string Name { get; set; } } public class Student : Person { } public class Teacher : Person { } public class C { public void M(Person p) { switch (p) { case Teacher { Name: var name }: Console.WriteLine($""Hello teacher { name}!""); break; case Student { Name: var name }: Console.WriteLine($""Hello student { name}!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 80 (0x50) .maxstack 3 .locals init (string V_0, //name string V_1) //name IL_0000: ldarg.1 IL_0001: isinst ""Teacher"" IL_0006: brfalse.s IL_0011 IL_0008: ldarg.1 IL_0009: callvirt ""string Person.Name.get"" IL_000e: stloc.0 IL_000f: br.s IL_0022 IL_0011: ldarg.1 IL_0012: isinst ""Student"" IL_0017: brfalse.s IL_004f IL_0019: ldarg.1 IL_001a: callvirt ""string Person.Name.get"" IL_001f: stloc.0 IL_0020: br.s IL_0038 IL_0022: ldstr ""Hello teacher "" IL_0027: ldloc.0 IL_0028: ldstr ""!"" IL_002d: call ""string string.Concat(string, string, string)"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret IL_0038: ldloc.0 IL_0039: stloc.1 IL_003a: ldstr ""Hello student "" IL_003f: ldloc.1 IL_0040: ldstr ""!"" IL_0045: call ""string string.Concat(string, string, string)"" IL_004a: call ""void System.Console.WriteLine(string)"" IL_004f: ret } "); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead06() { var source = @"using System; public class Person { public string Name { get; set; } } public class Student : Person { } public class C { public void M(Person p) { switch (p) { case { Name: { Length: 0 } }: Console.WriteLine(""Hello!""); break; case Student { Name: { Length : 1 } }: Console.WriteLine($""Hello student!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 58 (0x3a) .maxstack 2 .locals init (string V_0, int V_1) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0039 IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0039 IL_000d: ldloc.0 IL_000e: callvirt ""int string.Length.get"" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_0024 IL_0017: ldarg.1 IL_0018: isinst ""Student"" IL_001d: brfalse.s IL_0039 IL_001f: ldloc.1 IL_0020: ldc.i4.1 IL_0021: beq.s IL_002f IL_0023: ret IL_0024: ldstr ""Hello!"" IL_0029: call ""void System.Console.WriteLine(string)"" IL_002e: ret IL_002f: ldstr ""Hello student!"" IL_0034: call ""void System.Console.WriteLine(string)"" IL_0039: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead07() { // Cannot combine the evaluations of name here, since we first check if name is MemoryStream, // and only if that fails check if name is null. // Combining the evaluations would mean first checking if name is null, then evaluating name, then checking if p is Teacher. // This would not necessarily be more performant. var source = @"using System; using System.IO; public class Person { public Stream Name { get; set; } } public class C { public void M(Person p) { switch (p) { case Person { Name: MemoryStream { Length: 1 } }: Console.WriteLine(""Your Names A MemoryStream!""); break; case Person { Name: { Length : var x } }: Console.WriteLine(""Your Names A Stream!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 66 (0x42) .maxstack 2 .locals init (System.IO.Stream V_0, System.IO.MemoryStream V_1) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0041 IL_0003: ldarg.1 IL_0004: callvirt ""System.IO.Stream Person.Name.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: isinst ""System.IO.MemoryStream"" IL_0010: stloc.1 IL_0011: ldloc.1 IL_0012: brfalse.s IL_0020 IL_0014: ldloc.1 IL_0015: callvirt ""long System.IO.Stream.Length.get"" IL_001a: ldc.i4.1 IL_001b: conv.i8 IL_001c: beq.s IL_002c IL_001e: br.s IL_0023 IL_0020: ldloc.0 IL_0021: brfalse.s IL_0041 IL_0023: ldloc.0 IL_0024: callvirt ""long System.IO.Stream.Length.get"" IL_0029: pop IL_002a: br.s IL_0037 IL_002c: ldstr ""Your Names A MemoryStream!"" IL_0031: call ""void System.Console.WriteLine(string)"" IL_0036: ret IL_0037: ldstr ""Your Names A Stream!"" IL_003c: call ""void System.Console.WriteLine(string)"" IL_0041: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead08() { var source = @" public class Person { public string Name { get; set; } } public class Student : Person { } public class C { public string M(Person p) { return p switch { { Name: ""Bill"" } => ""Hey Bill!"", Student { Name: var name } => ""Hello student { name}!"", _ => null, }; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 51 (0x33) .maxstack 2 .locals init (string V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_002f IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: ldstr ""Bill"" IL_000e: call ""bool string.op_Equality(string, string)"" IL_0013: brtrue.s IL_001f IL_0015: ldarg.1 IL_0016: isinst ""Student"" IL_001b: brtrue.s IL_0027 IL_001d: br.s IL_002f IL_001f: ldstr ""Hey Bill!"" IL_0024: stloc.0 IL_0025: br.s IL_0031 IL_0027: ldstr ""Hello student { name}!"" IL_002c: stloc.0 IL_002d: br.s IL_0031 IL_002f: ldnull IL_0030: stloc.0 IL_0031: ldloc.0 IL_0032: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead09() { var source = @"using System; public class Person { public virtual string Name { get; set; } } public class Student : Person { } public class C { public void M(Person p) { switch (p) { case { Name: ""Bill"" }: Console.WriteLine(""Hey Bill!""); break; case Student { Name: var name }: Console.WriteLine($""Hello student { name}!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 65 (0x41) .maxstack 3 .locals init (string V_0) //name IL_0000: ldarg.1 IL_0001: brfalse.s IL_0040 IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldstr ""Bill"" IL_0010: call ""bool string.op_Equality(string, string)"" IL_0015: brtrue.s IL_0020 IL_0017: ldarg.1 IL_0018: isinst ""Student"" IL_001d: brtrue.s IL_002b IL_001f: ret IL_0020: ldstr ""Hey Bill!"" IL_0025: call ""void System.Console.WriteLine(string)"" IL_002a: ret IL_002b: ldstr ""Hello student "" IL_0030: ldloc.0 IL_0031: ldstr ""!"" IL_0036: call ""string string.Concat(string, string, string)"" IL_003b: call ""void System.Console.WriteLine(string)"" IL_0040: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead10() { // Currently we don't combine these redundant property reads. // However we could do so in the future. var source = @"using System; public abstract class Person { public abstract string Name { get; set; } } public class Student : Person { public override string Name { get; set; } } public class C { public void M(Person p) { switch (p) { case { Name: ""Bill"" }: Console.WriteLine(""Hey Bill!""); break; case Student { Name: var name }: Console.WriteLine($""Hello student { name}!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 73 (0x49) .maxstack 3 .locals init (string V_0, //name Student V_1) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0048 IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: ldstr ""Bill"" IL_000e: call ""bool string.op_Equality(string, string)"" IL_0013: brtrue.s IL_0028 IL_0015: ldarg.1 IL_0016: isinst ""Student"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: brfalse.s IL_0048 IL_001f: ldloc.1 IL_0020: callvirt ""string Person.Name.get"" IL_0025: stloc.0 IL_0026: br.s IL_0033 IL_0028: ldstr ""Hey Bill!"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ret IL_0033: ldstr ""Hello student "" IL_0038: ldloc.0 IL_0039: ldstr ""!"" IL_003e: call ""string string.Concat(string, string, string)"" IL_0043: call ""void System.Console.WriteLine(string)"" IL_0048: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void CombiningRedundantPropertyReadsDoesNotChangeNullabilityAnalysis01() { // Currently we don't combine the redundant property reads at all. // However this could be improved in the future so this test is important var source = @"using System; #nullable enable public class Person { public virtual string? Name { get; } } public class Student : Person { public override string Name { get => base.Name ?? """"; } } public class C { public void M(Person p) { switch (p) { case { Name: ""Bill""}: Console.WriteLine(""Hey Bill!""); break; case Student { Name: var name }: Console.WriteLine($""Student has name of length { name.Length }!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 78 (0x4e) .maxstack 2 .locals init (string V_0, //name Student V_1) IL_0000: ldarg.1 IL_0001: brfalse.s IL_004d IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: ldstr ""Bill"" IL_000e: call ""bool string.op_Equality(string, string)"" IL_0013: brtrue.s IL_0028 IL_0015: ldarg.1 IL_0016: isinst ""Student"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: brfalse.s IL_004d IL_001f: ldloc.1 IL_0020: callvirt ""string Person.Name.get"" IL_0025: stloc.0 IL_0026: br.s IL_0033 IL_0028: ldstr ""Hey Bill!"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ret IL_0033: ldstr ""Student has name of length {0}!"" IL_0038: ldloc.0 IL_0039: callvirt ""int string.Length.get"" IL_003e: box ""int"" IL_0043: call ""string string.Format(string, object)"" IL_0048: call ""void System.Console.WriteLine(string)"" IL_004d: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void CombiningRedundantPropertyReadsDoesNotChangeNullabilityAnalysis02() { var source = @"using System; #nullable enable public class Person { public string? Name { get;} } public class Student : Person { } public class C { public void M(Person p) { switch (p) { case { Name: var name } when name is null: Console.WriteLine($""Hey { name }""); break; case Student { Name: var name } when name != null: Console.WriteLine($""Student has name of length { name.Length }!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 75 (0x4b) .maxstack 2 .locals init (string V_0, //name string V_1, //name Person V_2) IL_0000: ldarg.1 IL_0001: stloc.2 IL_0002: ldloc.2 IL_0003: brfalse.s IL_004a IL_0005: ldloc.2 IL_0006: callvirt ""string Person.Name.get"" IL_000b: stloc.0 IL_000c: br.s IL_0017 IL_000e: ldloc.2 IL_000f: isinst ""Student"" IL_0014: brtrue.s IL_002b IL_0016: ret IL_0017: ldloc.0 IL_0018: brtrue.s IL_000e IL_001a: ldstr ""Hey "" IL_001f: ldloc.0 IL_0020: call ""string string.Concat(string, string)"" IL_0025: call ""void System.Console.WriteLine(string)"" IL_002a: ret IL_002b: ldloc.0 IL_002c: stloc.1 IL_002d: ldloc.1 IL_002e: brfalse.s IL_004a IL_0030: ldstr ""Student has name of length {0}!"" IL_0035: ldloc.1 IL_0036: callvirt ""int string.Length.get"" IL_003b: box ""int"" IL_0040: call ""string string.Format(string, object)"" IL_0045: call ""void System.Console.WriteLine(string)"" IL_004a: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void CombiningRedundantPropertyReadsDoesNotChangeNullabilityAnalysis03() { var source = @"using System; #nullable enable public class Person { public string? Name { get; } } public class Student : Person { } public class C { public void M(Person p) { switch (p) { case { Name: string name }: Console.WriteLine($""Hey {name}""); break; case Student { Name: var name }: Console.WriteLine($""Student has name of length { name.Length }!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (19,66): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine($"Student has name of length { name.Length }!"); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "name").WithLocation(19, 66)); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 68 (0x44) .maxstack 2 .locals init (string V_0, //name string V_1) //name IL_0000: ldarg.1 IL_0001: brfalse.s IL_0043 IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brtrue.s IL_0016 IL_000d: ldarg.1 IL_000e: isinst ""Student"" IL_0013: brtrue.s IL_0027 IL_0015: ret IL_0016: ldstr ""Hey "" IL_001b: ldloc.0 IL_001c: call ""string string.Concat(string, string)"" IL_0021: call ""void System.Console.WriteLine(string)"" IL_0026: ret IL_0027: ldloc.0 IL_0028: stloc.1 IL_0029: ldstr ""Student has name of length {0}!"" IL_002e: ldloc.1 IL_002f: callvirt ""int string.Length.get"" IL_0034: box ""int"" IL_0039: call ""string string.Format(string, object)"" IL_003e: call ""void System.Console.WriteLine(string)"" IL_0043: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void DoNotCombineDifferentPropertyReadsWithSameName() { var source = @"using System; public class Person { public string Name { get; set; } } public class Student : Person { public new string Name { get; set; } } public class C { public void M(Person p) { switch (p) { case { Name: ""Bill"" }: Console.WriteLine(""Hey Bill!""); break; case Student { Name: var name }: Console.WriteLine($""Hello student { name}!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 73 (0x49) .maxstack 3 .locals init (string V_0, //name Student V_1) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0048 IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: ldstr ""Bill"" IL_000e: call ""bool string.op_Equality(string, string)"" IL_0013: brtrue.s IL_0028 IL_0015: ldarg.1 IL_0016: isinst ""Student"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: brfalse.s IL_0048 IL_001f: ldloc.1 IL_0020: callvirt ""string Student.Name.get"" IL_0025: stloc.0 IL_0026: br.s IL_0033 IL_0028: ldstr ""Hey Bill!"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ret IL_0033: ldstr ""Hello student "" IL_0038: ldloc.0 IL_0039: ldstr ""!"" IL_003e: call ""string string.Concat(string, string, string)"" IL_0043: call ""void System.Console.WriteLine(string)"" IL_0048: ret }"); } [Fact, WorkItem(51801, "https://github.com/dotnet/roslyn/issues/51801")] public void PropertyOverrideLacksAccessor() { var source = @" #nullable enable class Base { public virtual bool IsOk { get { return true; } set { } } } class C : Base { public override bool IsOk { set { } } public string? Value { get; } public string M() { switch (this) { case { IsOk: true }: return Value; default: return Value; } } } "; var verifier = CompileAndVerify(source); verifier.VerifyIL("C.M", @" { // Code size 26 (0x1a) .maxstack 1 .locals init (C V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brfalse.s IL_0013 IL_0005: ldloc.0 IL_0006: callvirt ""bool Base.IsOk.get"" IL_000b: pop IL_000c: ldarg.0 IL_000d: call ""string C.Value.get"" IL_0012: ret IL_0013: ldarg.0 IL_0014: call ""string C.Value.get"" IL_0019: ret }"); } [Fact, WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")] public void PatternsVsAs01() { var source = @"using System.Collections; using System.Collections.Generic; class Program { static void Main() { } internal static bool TryGetCount1<T>(IEnumerable<T> source, out int count) { ICollection nonGeneric = source as ICollection; if (nonGeneric != null) { count = nonGeneric.Count; return true; } ICollection<T> generic = source as ICollection<T>; if (generic != null) { count = generic.Count; return true; } count = -1; return false; } internal static bool TryGetCount2<T>(IEnumerable<T> source, out int count) { switch (source) { case ICollection nonGeneric: count = nonGeneric.Count; return true; case ICollection<T> generic: count = generic.Count; return true; default: count = -1; return false; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("Program.TryGetCount1<T>", @"{ // Code size 45 (0x2d) .maxstack 2 .locals init (System.Collections.ICollection V_0, //nonGeneric System.Collections.Generic.ICollection<T> V_1) //generic IL_0000: ldarg.0 IL_0001: isinst ""System.Collections.ICollection"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0014 IL_000a: ldarg.1 IL_000b: ldloc.0 IL_000c: callvirt ""int System.Collections.ICollection.Count.get"" IL_0011: stind.i4 IL_0012: ldc.i4.1 IL_0013: ret IL_0014: ldarg.0 IL_0015: isinst ""System.Collections.Generic.ICollection<T>"" IL_001a: stloc.1 IL_001b: ldloc.1 IL_001c: brfalse.s IL_0028 IL_001e: ldarg.1 IL_001f: ldloc.1 IL_0020: callvirt ""int System.Collections.Generic.ICollection<T>.Count.get"" IL_0025: stind.i4 IL_0026: ldc.i4.1 IL_0027: ret IL_0028: ldarg.1 IL_0029: ldc.i4.m1 IL_002a: stind.i4 IL_002b: ldc.i4.0 IL_002c: ret }"); compVerifier.VerifyIL("Program.TryGetCount2<T>", @"{ // Code size 47 (0x2f) .maxstack 2 .locals init (System.Collections.ICollection V_0, //nonGeneric System.Collections.Generic.ICollection<T> V_1) //generic IL_0000: ldarg.0 IL_0001: isinst ""System.Collections.ICollection"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0016 IL_000a: ldarg.0 IL_000b: isinst ""System.Collections.Generic.ICollection<T>"" IL_0010: stloc.1 IL_0011: ldloc.1 IL_0012: brtrue.s IL_0020 IL_0014: br.s IL_002a IL_0016: ldarg.1 IL_0017: ldloc.0 IL_0018: callvirt ""int System.Collections.ICollection.Count.get"" IL_001d: stind.i4 IL_001e: ldc.i4.1 IL_001f: ret IL_0020: ldarg.1 IL_0021: ldloc.1 IL_0022: callvirt ""int System.Collections.Generic.ICollection<T>.Count.get"" IL_0027: stind.i4 IL_0028: ldc.i4.1 IL_0029: ret IL_002a: ldarg.1 IL_002b: ldc.i4.m1 IL_002c: stind.i4 IL_002d: ldc.i4.0 IL_002e: ret }"); } [Fact, WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")] public void PatternsVsAs02() { var source = @"using System.Collections; class Program { static void Main() { } internal static bool IsEmpty1(IEnumerable source) { var c = source as ICollection; return c != null && c.Count > 0; } internal static bool IsEmpty2(IEnumerable source) { return source is ICollection c && c.Count > 0; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("Program.IsEmpty1", @"{ // Code size 22 (0x16) .maxstack 2 .locals init (System.Collections.ICollection V_0) //c IL_0000: ldarg.0 IL_0001: isinst ""System.Collections.ICollection"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0014 IL_000a: ldloc.0 IL_000b: callvirt ""int System.Collections.ICollection.Count.get"" IL_0010: ldc.i4.0 IL_0011: cgt IL_0013: ret IL_0014: ldc.i4.0 IL_0015: ret }"); compVerifier.VerifyIL("Program.IsEmpty2", @"{ // Code size 22 (0x16) .maxstack 2 .locals init (System.Collections.ICollection V_0) //c IL_0000: ldarg.0 IL_0001: isinst ""System.Collections.ICollection"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0014 IL_000a: ldloc.0 IL_000b: callvirt ""int System.Collections.ICollection.Count.get"" IL_0010: ldc.i4.0 IL_0011: cgt IL_0013: ret IL_0014: ldc.i4.0 IL_0015: ret }"); } [Fact] [WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")] [WorkItem(1395, "https://github.com/dotnet/csharplang/issues/1395")] public void TupleSwitch01() { var source = @"using System; public class Door { public DoorState State; public enum DoorState { Opened, Closed, Locked } public enum Action { Open, Close, Lock, Unlock } public void Act0(Action action, bool haveKey = false) { Console.Write($""{State} {action}{(haveKey ? "" withKey"" : null)}""); State = ChangeState0(State, action, haveKey); Console.WriteLine($"" -> {State}""); } public void Act1(Action action, bool haveKey = false) { Console.Write($""{State} {action}{(haveKey ? "" withKey"" : null)}""); State = ChangeState1(State, action, haveKey); Console.WriteLine($"" -> {State}""); } public static DoorState ChangeState0(DoorState state, Action action, bool haveKey = false) { switch (state, action) { case (DoorState.Opened, Action.Close): return DoorState.Closed; case (DoorState.Closed, Action.Open): return DoorState.Opened; case (DoorState.Closed, Action.Lock) when haveKey: return DoorState.Locked; case (DoorState.Locked, Action.Unlock) when haveKey: return DoorState.Closed; case var (oldState, _): return oldState; } } public static DoorState ChangeState1(DoorState state, Action action, bool haveKey = false) => (state, action) switch { (DoorState.Opened, Action.Close) => DoorState.Closed, (DoorState.Closed, Action.Open) => DoorState.Opened, (DoorState.Closed, Action.Lock) when haveKey => DoorState.Locked, (DoorState.Locked, Action.Unlock) when haveKey => DoorState.Closed, _ => state }; } class Program { static void Main(string[] args) { var door = new Door(); door.Act0(Door.Action.Close); door.Act0(Door.Action.Lock); door.Act0(Door.Action.Lock, true); door.Act0(Door.Action.Open); door.Act0(Door.Action.Unlock); door.Act0(Door.Action.Unlock, true); door.Act0(Door.Action.Open); Console.WriteLine(); door = new Door(); door.Act1(Door.Action.Close); door.Act1(Door.Action.Lock); door.Act1(Door.Action.Lock, true); door.Act1(Door.Action.Open); door.Act1(Door.Action.Unlock); door.Act1(Door.Action.Unlock, true); door.Act1(Door.Action.Open); } }"; var expectedOutput = @"Opened Close -> Closed Closed Lock -> Closed Closed Lock withKey -> Locked Locked Open -> Locked Locked Unlock -> Locked Locked Unlock withKey -> Closed Closed Open -> Opened Opened Close -> Closed Closed Lock -> Closed Closed Lock withKey -> Locked Locked Open -> Locked Locked Unlock -> Locked Locked Unlock withKey -> Closed Closed Open -> Opened "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithRecursivePatterns); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("Door.ChangeState0", @"{ // Code size 61 (0x3d) .maxstack 2 .locals init (Door.DoorState V_0, //oldState Door.Action V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: switch ( IL_0018, IL_001e, IL_0027) IL_0016: br.s IL_003b IL_0018: ldloc.1 IL_0019: ldc.i4.1 IL_001a: beq.s IL_002d IL_001c: br.s IL_003b IL_001e: ldloc.1 IL_001f: brfalse.s IL_002f IL_0021: ldloc.1 IL_0022: ldc.i4.2 IL_0023: beq.s IL_0031 IL_0025: br.s IL_003b IL_0027: ldloc.1 IL_0028: ldc.i4.3 IL_0029: beq.s IL_0036 IL_002b: br.s IL_003b IL_002d: ldc.i4.1 IL_002e: ret IL_002f: ldc.i4.0 IL_0030: ret IL_0031: ldarg.2 IL_0032: brfalse.s IL_003b IL_0034: ldc.i4.2 IL_0035: ret IL_0036: ldarg.2 IL_0037: brfalse.s IL_003b IL_0039: ldc.i4.1 IL_003a: ret IL_003b: ldloc.0 IL_003c: ret }"); compVerifier.VerifyIL("Door.ChangeState1", @"{ // Code size 71 (0x47) .maxstack 2 .locals init (Door.DoorState V_0, Door.DoorState V_1, Door.Action V_2) IL_0000: ldarg.0 IL_0001: stloc.1 IL_0002: ldarg.1 IL_0003: stloc.2 IL_0004: ldloc.1 IL_0005: switch ( IL_0018, IL_001e, IL_0027) IL_0016: br.s IL_0043 IL_0018: ldloc.2 IL_0019: ldc.i4.1 IL_001a: beq.s IL_002d IL_001c: br.s IL_0043 IL_001e: ldloc.2 IL_001f: brfalse.s IL_0031 IL_0021: ldloc.2 IL_0022: ldc.i4.2 IL_0023: beq.s IL_0035 IL_0025: br.s IL_0043 IL_0027: ldloc.2 IL_0028: ldc.i4.3 IL_0029: beq.s IL_003c IL_002b: br.s IL_0043 IL_002d: ldc.i4.1 IL_002e: stloc.0 IL_002f: br.s IL_0045 IL_0031: ldc.i4.0 IL_0032: stloc.0 IL_0033: br.s IL_0045 IL_0035: ldarg.2 IL_0036: brfalse.s IL_0043 IL_0038: ldc.i4.2 IL_0039: stloc.0 IL_003a: br.s IL_0045 IL_003c: ldarg.2 IL_003d: brfalse.s IL_0043 IL_003f: ldc.i4.1 IL_0040: stloc.0 IL_0041: br.s IL_0045 IL_0043: ldarg.0 IL_0044: stloc.0 IL_0045: ldloc.0 IL_0046: ret }"); } [Fact] [WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")] [WorkItem(1395, "https://github.com/dotnet/csharplang/issues/1395")] public void SharingTemps01() { var source = @"class Program { static void Main(string[] args) { } void M1(string x) { switch (x) { case ""a"": case ""b"" when Mutate(ref x): // prevents sharing temps case ""c"": break; } } void M2(string x) { switch (x) { case ""a"": case ""b"" when Pure(x): case ""c"": break; } } static bool Mutate(ref string x) { x = null; return false; } static bool Pure(string x) { return false; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithoutRecursivePatterns); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("Program.M1", @"{ // Code size 50 (0x32) .maxstack 2 .locals init (string V_0) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldstr ""a"" IL_0008: call ""bool string.op_Equality(string, string)"" IL_000d: brtrue.s IL_0031 IL_000f: ldloc.0 IL_0010: ldstr ""b"" IL_0015: call ""bool string.op_Equality(string, string)"" IL_001a: brtrue.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""c"" IL_0022: call ""bool string.op_Equality(string, string)"" IL_0027: pop IL_0028: ret IL_0029: ldarga.s V_1 IL_002b: call ""bool Program.Mutate(ref string)"" IL_0030: pop IL_0031: ret }"); compVerifier.VerifyIL("Program.M2", @"{ // Code size 49 (0x31) .maxstack 2 .locals init (string V_0) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldstr ""a"" IL_0008: call ""bool string.op_Equality(string, string)"" IL_000d: brtrue.s IL_0030 IL_000f: ldloc.0 IL_0010: ldstr ""b"" IL_0015: call ""bool string.op_Equality(string, string)"" IL_001a: brtrue.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""c"" IL_0022: call ""bool string.op_Equality(string, string)"" IL_0027: pop IL_0028: ret IL_0029: ldarg.1 IL_002a: call ""bool Program.Pure(string)"" IL_002f: pop IL_0030: ret }"); } [Fact, WorkItem(17266, "https://github.com/dotnet/roslyn/issues/17266")] public void IrrefutablePatternInIs01() { var source = @"using System; public class C { public static void Main() { if (Get() is int index) { } Console.WriteLine(index); } public static int Get() { Console.WriteLine(""eval""); return 1; } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"eval 1"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(17266, "https://github.com/dotnet/roslyn/issues/17266")] public void IrrefutablePatternInIs02() { var source = @"using System; public class C { public static void Main() { if (Get() is Assignment(int left, var right)) { } Console.WriteLine(left); Console.WriteLine(right); } public static Assignment Get() { Console.WriteLine(""eval""); return new Assignment(1, 2); } } public struct Assignment { public int Left, Right; public Assignment(int left, int right) => (Left, Right) = (left, right); public void Deconstruct(out int left, out int right) => (left, right) = (Left, Right); } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns); compilation.VerifyDiagnostics(); var expectedOutput = @"eval 1 2"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void MissingNullCheck01() { var source = @"class Program { public static void Main() { string s = null; System.Console.WriteLine(s is string { Length: 3 }); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns); compilation.VerifyDiagnostics(); var expectedOutput = @"False"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] [WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")] [WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")] public void ConstantPatternVsUnconstrainedTypeParameter01() { var source = @"using System; class Program { static void Main() { Console.WriteLine(Test1<object>(null)); Console.WriteLine(Test1<int>(1)); Console.WriteLine(Test1<int?>(null)); Console.WriteLine(Test1<int?>(1)); Console.WriteLine(Test2<object>(0)); Console.WriteLine(Test2<int>(1)); Console.WriteLine(Test2<int?>(0)); Console.WriteLine(Test2<string>(""frog"")); Console.WriteLine(Test3<object>(""frog"")); Console.WriteLine(Test3<int>(1)); Console.WriteLine(Test3<string>(""frog"")); Console.WriteLine(Test3<int?>(1)); } public static bool Test1<T>(T t) { return t is null; } public static bool Test2<T>(T t) { return t is 0; } public static bool Test3<T>(T t) { return t is ""frog""; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"True False True False True False True False True False True False "; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("Program.Test1<T>(T)", @"{ // Code size 10 (0xa) .maxstack 2 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: ldnull IL_0007: ceq IL_0009: ret }"); compVerifier.VerifyIL("Program.Test2<T>(T)", @"{ // Code size 35 (0x23) .maxstack 2 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0021 IL_000d: ldarg.0 IL_000e: box ""T"" IL_0013: isinst ""int"" IL_0018: unbox.any ""int"" IL_001d: ldc.i4.0 IL_001e: ceq IL_0020: ret IL_0021: ldc.i4.0 IL_0022: ret } "); compVerifier.VerifyIL("Program.Test3<T>(T)", @"{ // Code size 29 (0x1d) .maxstack 2 .locals init (string V_0) IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: isinst ""string"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brfalse.s IL_001b IL_000f: ldloc.0 IL_0010: ldstr ""frog"" IL_0015: call ""bool string.op_Equality(string, string)"" IL_001a: ret IL_001b: ldc.i4.0 IL_001c: ret }"); } [Fact] [WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")] [WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")] public void ConstantPatternVsUnconstrainedTypeParameter02() { var source = @"class C<T> { internal struct S { } static bool Test(S s) { return s is 1; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C<T>.Test(C<T>.S)", @"{ // Code size 35 (0x23) .maxstack 2 IL_0000: ldarg.0 IL_0001: box ""C<T>.S"" IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0021 IL_000d: ldarg.0 IL_000e: box ""C<T>.S"" IL_0013: isinst ""int"" IL_0018: unbox.any ""int"" IL_001d: ldc.i4.1 IL_001e: ceq IL_0020: ret IL_0021: ldc.i4.0 IL_0022: ret } "); } [Fact] [WorkItem(26274, "https://github.com/dotnet/roslyn/issues/26274")] public void VariablesInSwitchExpressionArms() { var source = @"class C { public override bool Equals(object obj) => obj switch { C x1 when x1 is var x2 => x2 is var x3 && x3 is {}, _ => false }; public override int GetHashCode() => 1; public static void Main() { C c = new C(); System.Console.Write(c.Equals(new C())); System.Console.Write(c.Equals(new object())); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "TrueFalse"); compVerifier.VerifyIL("C.Equals(object)", @"{ // Code size 25 (0x19) .maxstack 2 .locals init (C V_0, //x1 C V_1, //x2 C V_2, //x3 bool V_3) IL_0000: ldarg.1 IL_0001: isinst ""C"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0015 IL_000a: ldloc.0 IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: stloc.2 IL_000e: ldloc.2 IL_000f: ldnull IL_0010: cgt.un IL_0012: stloc.3 IL_0013: br.s IL_0017 IL_0015: ldc.i4.0 IL_0016: stloc.3 IL_0017: ldloc.3 IL_0018: ret }"); } [Fact, WorkItem(26387, "https://github.com/dotnet/roslyn/issues/26387")] public void ValueTypeArgument01() { var source = @"using System; class TestHelper { static void Main() { Console.WriteLine(IsValueTypeT0(new S())); Console.WriteLine(IsValueTypeT1(new S())); Console.WriteLine(IsValueTypeT2(new S())); } static bool IsValueTypeT0<T>(T result) { return result is T; } static bool IsValueTypeT1<T>(T result) { return result is T v; } static bool IsValueTypeT2<T>(T result) { return result is T _; } } struct S { } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"True True True"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("TestHelper.IsValueTypeT0<T>(T)", @"{ // Code size 15 (0xf) .maxstack 2 .locals init (bool V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: ldnull IL_0008: cgt.un IL_000a: stloc.0 IL_000b: br.s IL_000d IL_000d: ldloc.0 IL_000e: ret }"); compVerifier.VerifyIL("TestHelper.IsValueTypeT1<T>(T)", @"{ // Code size 20 (0x14) .maxstack 1 .locals init (T V_0, //v bool V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: brfalse.s IL_000e IL_0009: ldarg.0 IL_000a: stloc.0 IL_000b: ldc.i4.1 IL_000c: br.s IL_000f IL_000e: ldc.i4.0 IL_000f: stloc.1 IL_0010: br.s IL_0012 IL_0012: ldloc.1 IL_0013: ret }"); compVerifier.VerifyIL("TestHelper.IsValueTypeT2<T>(T)", @"{ // Code size 15 (0xf) .maxstack 2 .locals init (bool V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: ldnull IL_0008: cgt.un IL_000a: stloc.0 IL_000b: br.s IL_000d IL_000d: ldloc.0 IL_000e: ret }"); } [Fact, WorkItem(26387, "https://github.com/dotnet/roslyn/issues/26387")] public void ValueTypeArgument02() { var source = @"namespace ConsoleApp1 { public class TestHelper { public static void Main() { IsValueTypeT(new Result<(Cls, IInt)>((new Cls(), new Int()))); System.Console.WriteLine(""done""); } public static void IsValueTypeT<T>(Result<T> result) { if (!(result.Value is T v)) throw new NotPossibleException(); } } public class Result<T> { public T Value { get; } public Result(T value) { Value = value; } } public class Cls { } public interface IInt { } public class Int : IInt { } public class NotPossibleException : System.Exception { } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"done"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("ConsoleApp1.TestHelper.IsValueTypeT<T>(ConsoleApp1.Result<T>)", @"{ // Code size 31 (0x1f) .maxstack 2 .locals init (T V_0, //v bool V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: callvirt ""T ConsoleApp1.Result<T>.Value.get"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: box ""T"" IL_000e: ldnull IL_000f: cgt.un IL_0011: ldc.i4.0 IL_0012: ceq IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001e IL_0018: newobj ""ConsoleApp1.NotPossibleException..ctor()"" IL_001d: throw IL_001e: ret }"); } [Fact] public void DeconstructNullableTuple_01() { var source = @" class C { static int i = 3; static (int,int)? GetNullableTuple() => (i++, i++); static void Main() { if (GetNullableTuple() is (int x1, int y1) tupl1) { System.Console.WriteLine($""x = {x1}, y = {y1}""); } if (GetNullableTuple() is (int x2, int y2) _) { System.Console.WriteLine($""x = {x2}, y = {y2}""); } switch (GetNullableTuple()) { case (int x3, int y3) s: System.Console.WriteLine($""x = {x3}, y = {y3}""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"x = 3, y = 4 x = 5, y = 6 x = 7, y = 8"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void DeconstructNullable_01() { var source = @" class C { static int i = 3; static S? GetNullableTuple() => new S(i++, i++); static void Main() { if (GetNullableTuple() is (int x1, int y1) tupl1) { System.Console.WriteLine($""x = {x1}, y = {y1}""); } if (GetNullableTuple() is (int x2, int y2) _) { System.Console.WriteLine($""x = {x2}, y = {y2}""); } switch (GetNullableTuple()) { case (int x3, int y3) s: System.Console.WriteLine($""x = {x3}, y = {y3}""); break; } } } struct S { int x, y; public S(int X, int Y) => (this.x, this.y) = (X, Y); public void Deconstruct(out int X, out int Y) => (X, Y) = (x, y); } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"x = 3, y = 4 x = 5, y = 6 x = 7, y = 8"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(28632, "https://github.com/dotnet/roslyn/issues/28632")] public void UnboxNullableInRecursivePattern01() { var source = @" static class Program { public static int M1(int? x) { return x is int y ? y : 1; } public static int M2(int? x) { return x is { } y ? y : 2; } public static void Main() { System.Console.WriteLine(M1(null)); System.Console.WriteLine(M2(null)); System.Console.WriteLine(M1(3)); System.Console.WriteLine(M2(4)); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"1 2 3 4"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("Program.M1", @"{ // Code size 23 (0x17) .maxstack 1 .locals init (int V_0) //y IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brfalse.s IL_0013 IL_0009: ldarga.s V_0 IL_000b: call ""int int?.GetValueOrDefault()"" IL_0010: stloc.0 IL_0011: br.s IL_0015 IL_0013: ldc.i4.1 IL_0014: ret IL_0015: ldloc.0 IL_0016: ret }"); compVerifier.VerifyIL("Program.M2", @"{ // Code size 23 (0x17) .maxstack 1 .locals init (int V_0) //y IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brfalse.s IL_0013 IL_0009: ldarga.s V_0 IL_000b: call ""int int?.GetValueOrDefault()"" IL_0010: stloc.0 IL_0011: br.s IL_0015 IL_0013: ldc.i4.2 IL_0014: ret IL_0015: ldloc.0 IL_0016: ret }"); } [Fact] public void DoNotShareInputForMutatingWhenClause() { var source = @"using System; class Program { static void Main() { Console.Write(M1(1)); Console.Write(M2(1)); Console.Write(M3(1)); Console.Write(M4(1)); Console.Write(M5(1)); Console.Write(M6(1)); Console.Write(M7(1)); Console.Write(M8(1)); Console.Write(M9(1)); } public static int M1(int x) { return x switch { _ when (++x) == 5 => 1, 1 => 2, _ => 3 }; } public static int M2(int x) { return x switch { _ when (x+=1) == 5 => 1, 1 => 2, _ => 3 }; } public static int M3(int x) { return x switch { _ when ((x, _) = (5, 6)) == (0, 0) => 1, 1 => 2, _ => 3 }; } public static int M4(int x) { dynamic d = new Program(); return x switch { _ when d.M(ref x) => 1, 1 => 2, _ => 3 }; } bool M(ref int x) { x = 100; return false; } public static int M5(int x) { return x switch { _ when new Program(ref x).P => 1, 1 => 2, _ => 3 }; } public static int M6(int x) { dynamic d = x; return x switch { _ when new Program(d, ref x).P => 1, 1 => 2, _ => 3 }; } public static int M7(int x) { return x switch { _ when new Program(ref x).P && new Program().P => 1, 1 => 2, _ => 3 }; } public static int M8(int x) { dynamic d = x; return x switch { _ when new Program(d, ref x).P && new Program().P => 1, 1 => 2, _ => 3 }; } public static int M9(int x) { return x switch { _ when (x=100) == 1 => 1, 1 => 2, _ => 3 }; } Program() { } Program(ref int x) { x = 100; } Program(int a, ref int x) { x = 100; } bool P => false; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, references: new[] { CSharpRef }); compilation.VerifyDiagnostics(); var expectedOutput = @"222222222"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void GenerateStringHashOnlyOnce() { var source = @"using System; class Program { static void Main() { Console.Write(M1(string.Empty)); Console.Write(M2(string.Empty)); } public static int M1(string s) { return s switch { ""a""=>1, ""b""=>2, ""c""=>3, ""d""=>4, ""e""=>5, ""f""=>6, ""g""=>7, ""h""=>8, _ => 9 }; } public static int M2(string s) { return s switch { ""a""=>1, ""b""=>2, ""c""=>3, ""d""=>4, ""e""=>5, ""f""=>6, ""g""=>7, ""h""=>8, _ => 9 }; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"99"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void BindVariablesInWhenClause() { var source = @"using System; class Program { static void Main() { var t = (1, 2); switch (t) { case var (x, y) when x+1 == y: Console.Write(1); break; } Console.Write(t switch { var (x, y) when x+1 == y => 1, _ => 2 }); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"11"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void MissingExceptions_01() { var source = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } static class C { public static bool M(int i) => i switch { 1 => true }; } "; var compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseDll); compilation.GetDiagnostics().Verify( // (9,38): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '0' is not covered. // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("0").WithLocation(9, 38) ); compilation.GetEmitDiagnostics().Verify( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (9,5): error CS0518: Predefined type 'System.Byte' is not defined or imported // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "public static bool M(int i) => i switch { 1 => true };").WithArguments("System.Byte").WithLocation(9, 5), // (9,5): error CS0518: Predefined type 'System.Byte' is not defined or imported // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "public static bool M(int i) => i switch { 1 => true };").WithArguments("System.Byte").WithLocation(9, 5), // (9,5): error CS0518: Predefined type 'System.Int16' is not defined or imported // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "public static bool M(int i) => i switch { 1 => true };").WithArguments("System.Int16").WithLocation(9, 5), // (9,5): error CS0518: Predefined type 'System.Int16' is not defined or imported // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "public static bool M(int i) => i switch { 1 => true };").WithArguments("System.Int16").WithLocation(9, 5), // (9,5): error CS0518: Predefined type 'System.Int64' is not defined or imported // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "public static bool M(int i) => i switch { 1 => true };").WithArguments("System.Int64").WithLocation(9, 5), // (9,5): error CS0518: Predefined type 'System.Int64' is not defined or imported // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "public static bool M(int i) => i switch { 1 => true };").WithArguments("System.Int64").WithLocation(9, 5), // (9,36): error CS0656: Missing compiler required member 'System.InvalidOperationException..ctor' // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "i switch { 1 => true }").WithArguments("System.InvalidOperationException", ".ctor").WithLocation(9, 36), // (9,38): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '0' is not covered. // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("0").WithLocation(9, 38) ); } [Fact, WorkItem(32774, "https://github.com/dotnet/roslyn/issues/32774")] public void BadCode_32774() { var source = @" public class Class1 { static void Main() { System.Console.WriteLine(SwitchCaseThatFails(12.123)); } public static bool SwitchCaseThatFails(object someObject) { switch (someObject) { case IObject x when x.SubObject != null: return false; case IOtherObject x: return false; case double x: return true; default: return false; } } public interface IObject { IObject SubObject { get; } } public interface IOtherObject { } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"True"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("Class1.SwitchCaseThatFails", @"{ // Code size 97 (0x61) .maxstack 1 .locals init (Class1.IObject V_0, //x Class1.IOtherObject V_1, //x double V_2, //x object V_3, object V_4, bool V_5) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.s V_4 IL_0004: ldloc.s V_4 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: isinst ""Class1.IObject"" IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: brtrue.s IL_003c IL_0011: br.s IL_001f IL_0013: ldloc.3 IL_0014: isinst ""Class1.IOtherObject"" IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: brtrue.s IL_004b IL_001d: br.s IL_0059 IL_001f: ldloc.3 IL_0020: isinst ""Class1.IOtherObject"" IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: brtrue.s IL_004b IL_0029: br.s IL_002b IL_002b: ldloc.3 IL_002c: isinst ""double"" IL_0031: brfalse.s IL_0059 IL_0033: ldloc.3 IL_0034: unbox.any ""double"" IL_0039: stloc.2 IL_003a: br.s IL_0052 IL_003c: ldloc.0 IL_003d: callvirt ""Class1.IObject Class1.IObject.SubObject.get"" IL_0042: brtrue.s IL_0046 IL_0044: br.s IL_0013 IL_0046: ldc.i4.0 IL_0047: stloc.s V_5 IL_0049: br.s IL_005e IL_004b: br.s IL_004d IL_004d: ldc.i4.0 IL_004e: stloc.s V_5 IL_0050: br.s IL_005e IL_0052: br.s IL_0054 IL_0054: ldc.i4.1 IL_0055: stloc.s V_5 IL_0057: br.s IL_005e IL_0059: ldc.i4.0 IL_005a: stloc.s V_5 IL_005c: br.s IL_005e IL_005e: ldloc.s V_5 IL_0060: ret }"); } // Possible test helper bug on Linux; see https://github.com/dotnet/roslyn/issues/33356 [ConditionalFact(typeof(WindowsOnly))] public void SwitchExpressionSequencePoints() { string source = @" public class Program { public static void Main() { int i = 0; var y = (i switch { 0 => new Program(), 1 => new Program(), _ => new Program(), }).Chain(); y.Chain2(); } public Program Chain() => this; public Program Chain2() => this; } "; var v = CompileAndVerify(source, options: TestOptions.DebugExe); v.VerifyIL(qualifiedMethodName: "Program.Main", @" { // Code size 61 (0x3d) .maxstack 2 .locals init (int V_0, //i Program V_1, //y Program V_2) // sequence point: { IL_0000: nop // sequence point: int i = 0; IL_0001: ldc.i4.0 IL_0002: stloc.0 // sequence point: var y = (i s ... }).Chain() IL_0003: ldc.i4.1 IL_0004: brtrue.s IL_0007 // sequence point: switch ... } IL_0006: nop // sequence point: <hidden> IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_001a IL_0010: br.s IL_0022 // sequence point: new Program() IL_0012: newobj ""Program..ctor()"" IL_0017: stloc.2 IL_0018: br.s IL_002a // sequence point: new Program() IL_001a: newobj ""Program..ctor()"" IL_001f: stloc.2 IL_0020: br.s IL_002a // sequence point: new Program() IL_0022: newobj ""Program..ctor()"" IL_0027: stloc.2 IL_0028: br.s IL_002a // sequence point: <hidden> IL_002a: ldc.i4.1 IL_002b: brtrue.s IL_002e // sequence point: var y = (i s ... }).Chain() IL_002d: nop // sequence point: <hidden> IL_002e: ldloc.2 IL_002f: callvirt ""Program Program.Chain()"" IL_0034: stloc.1 // sequence point: y.Chain2(); IL_0035: ldloc.1 IL_0036: callvirt ""Program Program.Chain2()"" IL_003b: pop // sequence point: } IL_003c: ret } ", sequencePoints: "Program.Main", source: source); } [Fact, WorkItem(33675, "https://github.com/dotnet/roslyn/issues/33675")] public void ParsingParenthesizedExpressionAsPatternOfExpressionSwitch() { var source = @" public class Class1 { static void Main() { System.Console.Write(M(42)); System.Console.Write(M(41)); } static bool M(object o) { const int X = 42; return o switch { (X) => true, _ => false }; } }"; foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe }) { var compilation = CreateCompilation(source, options: options); compilation.VerifyDiagnostics(); var expectedOutput = @"TrueFalse"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); if (options.OptimizationLevel == OptimizationLevel.Debug) { compVerifier.VerifyIL("Class1.M", @" { // Code size 45 (0x2d) .maxstack 2 .locals init (bool V_0, int V_1, bool V_2) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: isinst ""int"" IL_000b: brfalse.s IL_001f IL_000d: ldarg.0 IL_000e: unbox.any ""int"" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: ldc.i4.s 42 IL_0017: beq.s IL_001b IL_0019: br.s IL_001f IL_001b: ldc.i4.1 IL_001c: stloc.0 IL_001d: br.s IL_0023 IL_001f: ldc.i4.0 IL_0020: stloc.0 IL_0021: br.s IL_0023 IL_0023: ldc.i4.1 IL_0024: brtrue.s IL_0027 IL_0026: nop IL_0027: ldloc.0 IL_0028: stloc.2 IL_0029: br.s IL_002b IL_002b: ldloc.2 IL_002c: ret } "); } else { compVerifier.VerifyIL("Class1.M", @"{ // Code size 26 (0x1a) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: isinst ""int"" IL_0006: brfalse.s IL_0016 IL_0008: ldarg.0 IL_0009: unbox.any ""int"" IL_000e: ldc.i4.s 42 IL_0010: bne.un.s IL_0016 IL_0012: ldc.i4.1 IL_0013: stloc.0 IL_0014: br.s IL_0018 IL_0016: ldc.i4.0 IL_0017: stloc.0 IL_0018: ldloc.0 IL_0019: ret }"); } } } [Fact, WorkItem(35584, "https://github.com/dotnet/roslyn/issues/35584")] public void MatchToTypeParameterUnbox_01() { var source = @" class Program { public static void Main() => System.Console.WriteLine(P<int>(0)); public static string P<T>(T t) => (t is object o) ? o.ToString() : string.Empty; } "; var expectedOutput = @"0"; foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe }) { var compilation = CreateCompilation(source, options: options); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); if (options.OptimizationLevel == OptimizationLevel.Debug) { compVerifier.VerifyIL("Program.P<T>", @"{ // Code size 24 (0x18) .maxstack 1 .locals init (object V_0) //o IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0011 IL_000a: ldsfld ""string string.Empty"" IL_000f: br.s IL_0017 IL_0011: ldloc.0 IL_0012: callvirt ""string object.ToString()"" IL_0017: ret } "); } else { compVerifier.VerifyIL("Program.P<T>", @"{ // Code size 23 (0x17) .maxstack 1 .locals init (object V_0) //o IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0010 IL_000a: ldsfld ""string string.Empty"" IL_000f: ret IL_0010: ldloc.0 IL_0011: callvirt ""string object.ToString()"" IL_0016: ret } "); } } } [Fact, WorkItem(35584, "https://github.com/dotnet/roslyn/issues/35584")] public void MatchToTypeParameterUnbox_02() { var source = @"using System; class Program { public static void Main() { var generic = new Generic<int>(0); } } public class Generic<T> { public Generic(T value) { if (value is object obj && obj == null) { throw new Exception(""Kaboom!""); } } } "; var expectedOutput = @""; foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe }) { var compilation = CreateCompilation(source, options: options); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); if (options.OptimizationLevel == OptimizationLevel.Debug) { compVerifier.VerifyIL("Generic<T>..ctor(T)", @"{ // Code size 42 (0x2a) .maxstack 2 .locals init (object V_0, //obj bool V_1) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: nop IL_0008: ldarg.1 IL_0009: box ""T"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: brfalse.s IL_0018 IL_0012: ldloc.0 IL_0013: ldnull IL_0014: ceq IL_0016: br.s IL_0019 IL_0018: ldc.i4.0 IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: brfalse.s IL_0029 IL_001d: nop IL_001e: ldstr ""Kaboom!"" IL_0023: newobj ""System.Exception..ctor(string)"" IL_0028: throw IL_0029: ret } "); } else { compVerifier.VerifyIL("Generic<T>..ctor(T)", @"{ // Code size 31 (0x1f) .maxstack 1 .locals init (object V_0) //obj IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.1 IL_0007: box ""T"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: brfalse.s IL_001e IL_0010: ldloc.0 IL_0011: brtrue.s IL_001e IL_0013: ldstr ""Kaboom!"" IL_0018: newobj ""System.Exception..ctor(string)"" IL_001d: throw IL_001e: ret } "); } } } [Fact, WorkItem(35584, "https://github.com/dotnet/roslyn/issues/35584")] public void MatchToTypeParameterUnbox_03() { var source = @"using System; class Program { public static void Main() => System.Console.WriteLine(P<Enum>(null)); public static string P<T>(T t) where T: Enum => (t is ValueType o) ? o.ToString() : ""1""; } "; var expectedOutput = @"1"; foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe }) { var compilation = CreateCompilation(source, options: options); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); if (options.OptimizationLevel == OptimizationLevel.Debug) { compVerifier.VerifyIL("Program.P<T>", @"{ // Code size 24 (0x18) .maxstack 1 .locals init (System.ValueType V_0) //o IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0011 IL_000a: ldstr ""1"" IL_000f: br.s IL_0017 IL_0011: ldloc.0 IL_0012: callvirt ""string object.ToString()"" IL_0017: ret } "); } else { compVerifier.VerifyIL("Program.P<T>", @"{ // Code size 23 (0x17) .maxstack 1 .locals init (System.ValueType V_0) //o IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0010 IL_000a: ldstr ""1"" IL_000f: ret IL_0010: ldloc.0 IL_0011: callvirt ""string object.ToString()"" IL_0016: ret } "); } } } [Fact] public void CompileTimeRuntimeInstanceofMismatch_01() { var source = @"using System; class Program { static void Main() { M(new byte[1]); M(new sbyte[1]); M(new Ebyte[1]); M(new Esbyte[1]); M(new short[1]); M(new ushort[1]); M(new Eshort[1]); M(new Eushort[1]); M(new int[1]); M(new uint[1]); M(new Eint[1]); M(new Euint[1]); M(new int[1][]); M(new uint[1][]); M(new Eint[1][]); M(new Euint[1][]); M(new long[1]); M(new ulong[1]); M(new Elong[1]); M(new Eulong[1]); M(new IntPtr[1]); M(new UIntPtr[1]); M(new IntPtr[1][]); M(new UIntPtr[1][]); } static void M(object o) { switch (o) { case byte[] _ when o.GetType() == typeof(byte[]): Console.WriteLine(""byte[]""); break; case sbyte[] _ when o.GetType() == typeof(sbyte[]): Console.WriteLine(""sbyte[]""); break; case Ebyte[] _ when o.GetType() == typeof(Ebyte[]): Console.WriteLine(""Ebyte[]""); break; case Esbyte[] _ when o.GetType() == typeof(Esbyte[]): Console.WriteLine(""Esbyte[]""); break; case short[] _ when o.GetType() == typeof(short[]): Console.WriteLine(""short[]""); break; case ushort[] _ when o.GetType() == typeof(ushort[]): Console.WriteLine(""ushort[]""); break; case Eshort[] _ when o.GetType() == typeof(Eshort[]): Console.WriteLine(""Eshort[]""); break; case Eushort[] _ when o.GetType() == typeof(Eushort[]): Console.WriteLine(""Eushort[]""); break; case int[] _ when o.GetType() == typeof(int[]): Console.WriteLine(""int[]""); break; case uint[] _ when o.GetType() == typeof(uint[]): Console.WriteLine(""uint[]""); break; case Eint[] _ when o.GetType() == typeof(Eint[]): Console.WriteLine(""Eint[]""); break; case Euint[] _ when o.GetType() == typeof(Euint[]): Console.WriteLine(""Euint[]""); break; case int[][] _ when o.GetType() == typeof(int[][]): Console.WriteLine(""int[][]""); break; case uint[][] _ when o.GetType() == typeof(uint[][]): Console.WriteLine(""uint[][]""); break; case Eint[][] _ when o.GetType() == typeof(Eint[][]): Console.WriteLine(""Eint[][]""); break; case Euint[][] _ when o.GetType() == typeof(Euint[][]): Console.WriteLine(""Euint[][]""); break; case long[] _ when o.GetType() == typeof(long[]): Console.WriteLine(""long[]""); break; case ulong[] _ when o.GetType() == typeof(ulong[]): Console.WriteLine(""ulong[]""); break; case Elong[] _ when o.GetType() == typeof(Elong[]): Console.WriteLine(""Elong[]""); break; case Eulong[] _ when o.GetType() == typeof(Eulong[]): Console.WriteLine(""Eulong[]""); break; case IntPtr[] _ when o.GetType() == typeof(IntPtr[]): Console.WriteLine(""IntPtr[]""); break; case UIntPtr[] _ when o.GetType() == typeof(UIntPtr[]): Console.WriteLine(""UIntPtr[]""); break; case IntPtr[][] _ when o.GetType() == typeof(IntPtr[][]): Console.WriteLine(""IntPtr[][]""); break; case UIntPtr[][] _ when o.GetType() == typeof(UIntPtr[][]): Console.WriteLine(""UIntPtr[][]""); break; default: Console.WriteLine(""oops: "" + o.GetType()); break; } } } enum Ebyte : byte {} enum Esbyte : sbyte {} enum Eshort : short {} enum Eushort : ushort {} enum Eint : int {} enum Euint : uint {} enum Elong : long {} enum Eulong : ulong {} "; var expectedOutput = @"byte[] sbyte[] Ebyte[] Esbyte[] short[] ushort[] Eshort[] Eushort[] int[] uint[] Eint[] Euint[] int[][] uint[][] Eint[][] Euint[][] long[] ulong[] Elong[] Eulong[] IntPtr[] UIntPtr[] IntPtr[][] UIntPtr[][] "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: expectedOutput); compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void CompileTimeRuntimeInstanceofMismatch_02() { var source = @"using System; class Program { static void Main() { M(new byte[1]); M(new sbyte[1]); } static void M(object o) { switch (o) { case byte[] _: Console.WriteLine(""byte[]""); break; case sbyte[] _: // not subsumed, even though it will never occur due to CLR behavior Console.WriteLine(""sbyte[]""); break; } } } "; var expectedOutput = @"byte[] byte[] "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: expectedOutput); compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] [WorkItem(36496, "https://github.com/dotnet/roslyn/issues/36496")] public void EmptyVarPatternVsDeconstruct() { var source = @"using System; public class C { public static void Main() { Console.Write(M(new C())); Console.Write(M(null)); } public static bool M(C c) { return c is var (); } public void Deconstruct() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "TrueFalse"); compVerifier.VerifyIL("C.M(C)", @" { // Code size 5 (0x5) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldnull IL_0002: cgt.un IL_0004: ret } "); } [Fact] [WorkItem(36496, "https://github.com/dotnet/roslyn/issues/36496")] public void EmptyPositionalPatternVsDeconstruct() { var source = @"using System; public class C { public static void Main() { Console.Write(M(new C())); Console.Write(M(null)); } public static bool M(C c) { return c is (); } public void Deconstruct() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "TrueFalse"); compVerifier.VerifyIL("C.M(C)", @" { // Code size 5 (0x5) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldnull IL_0002: cgt.un IL_0004: ret } "); } [Fact, WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")] public void NoRedundantNullCheckForStringConstantPattern_01() { var source = @"public class C { public static bool M1(string s) => s is ""Frog""; public static bool M2(string s) => s == ""Frog""; public static bool M3(string s) => s switch { ""Frog"" => true, _ => false }; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1(string)", @" { // Code size 12 (0xc) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldstr ""Frog"" IL_0006: call ""bool string.op_Equality(string, string)"" IL_000b: ret } "); compVerifier.VerifyIL("C.M2(string)", @" { // Code size 12 (0xc) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldstr ""Frog"" IL_0006: call ""bool string.op_Equality(string, string)"" IL_000b: ret } "); compVerifier.VerifyIL("C.M3(string)", @" { // Code size 21 (0x15) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: ldstr ""Frog"" IL_0006: call ""bool string.op_Equality(string, string)"" IL_000b: brfalse.s IL_0011 IL_000d: ldc.i4.1 IL_000e: stloc.0 IL_000f: br.s IL_0013 IL_0011: ldc.i4.0 IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ret } "); } [Fact, WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")] public void NoRedundantNullCheckForStringConstantPattern_02() { var source = @"public class C { public static bool M1(string s) => s switch { ""Frog"" => true, ""Newt"" => true, _ => false }; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1(string)", @" { // Code size 40 (0x28) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: ldstr ""Frog"" IL_0006: call ""bool string.op_Equality(string, string)"" IL_000b: brtrue.s IL_001c IL_000d: ldarg.0 IL_000e: ldstr ""Newt"" IL_0013: call ""bool string.op_Equality(string, string)"" IL_0018: brtrue.s IL_0020 IL_001a: br.s IL_0024 IL_001c: ldc.i4.1 IL_001d: stloc.0 IL_001e: br.s IL_0026 IL_0020: ldc.i4.1 IL_0021: stloc.0 IL_0022: br.s IL_0026 IL_0024: ldc.i4.0 IL_0025: stloc.0 IL_0026: ldloc.0 IL_0027: ret } "); } [Fact, WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")] public void NoRedundantNullCheckForStringConstantPattern_03() { var source = @"public class C { public static bool M1(System.Type x) => x is { Name: ""Program"" }; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1(System.Type)", @" { // Code size 22 (0x16) .maxstack 2 IL_0000: ldarg.0 IL_0001: brfalse.s IL_0014 IL_0003: ldarg.0 IL_0004: callvirt ""string System.Reflection.MemberInfo.Name.get"" IL_0009: ldstr ""Program"" IL_000e: call ""bool string.op_Equality(string, string)"" IL_0013: ret IL_0014: ldc.i4.0 IL_0015: ret } "); } [Fact] [WorkItem(42912, "https://github.com/dotnet/roslyn/issues/42912")] [WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")] public void NoRedundantNullCheckForNullableConstantPattern_04() { // Note that we do not produce the same code for `x is 1` and `x == 1`. // The latter has been optimized to avoid branches. var source = @"public class C { public static bool M1(int? x) => x is 1; public static bool M2(int? x) => x == 1; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1(int?)", @" { // Code size 22 (0x16) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brfalse.s IL_0014 IL_0009: ldarga.s V_0 IL_000b: call ""int int?.GetValueOrDefault()"" IL_0010: ldc.i4.1 IL_0011: ceq IL_0013: ret IL_0014: ldc.i4.0 IL_0015: ret } "); compVerifier.VerifyIL("C.M2(int?)", @" { // Code size 23 (0x17) .maxstack 2 .locals init (int? V_0, int V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldc.i4.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""int int?.GetValueOrDefault()"" IL_000b: ldloc.1 IL_000c: ceq IL_000e: ldloca.s V_0 IL_0010: call ""bool int?.HasValue.get"" IL_0015: and IL_0016: ret } "); } [Fact] public void SwitchExpressionAsExceptionFilter_01() { var source = @" using System; class C { const string K1 = ""frog""; const string K2 = ""toad""; public static void M(string msg) { try { T(msg); } catch (Exception e) when (e.Message switch { K1 => true, K2 => true, _ => false, }) { throw new Exception(e.Message); } catch { } } static void T(string msg) { throw new Exception(msg); } static void Main() { Try(K1); Try(K2); Try(""fox""); } static void Try(string s) { try { M(s); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } "; var expectedOutput = @"frog toad"; foreach (var compilationOptions in new[] { TestOptions.ReleaseExe, TestOptions.DebugExe }) { var compilation = CreateCompilation(source, options: compilationOptions); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); if (compilationOptions.OptimizationLevel == OptimizationLevel.Debug) { compVerifier.VerifyIL("C.M(string)", @" { // Code size 108 (0x6c) .maxstack 2 .locals init (System.Exception V_0, //e bool V_1, string V_2, bool V_3) IL_0000: nop .try { IL_0001: nop IL_0002: ldarg.0 IL_0003: call ""void C.T(string)"" IL_0008: nop IL_0009: nop IL_000a: leave.s IL_006b } filter { IL_000c: isinst ""System.Exception"" IL_0011: dup IL_0012: brtrue.s IL_0018 IL_0014: pop IL_0015: ldc.i4.0 IL_0016: br.s IL_0056 IL_0018: stloc.0 IL_0019: ldloc.0 IL_001a: callvirt ""string System.Exception.Message.get"" IL_001f: stloc.2 IL_0020: ldc.i4.1 IL_0021: brtrue.s IL_0024 IL_0023: nop IL_0024: ldloc.2 IL_0025: ldstr ""frog"" IL_002a: call ""bool string.op_Equality(string, string)"" IL_002f: brtrue.s IL_0040 IL_0031: ldloc.2 IL_0032: ldstr ""toad"" IL_0037: call ""bool string.op_Equality(string, string)"" IL_003c: brtrue.s IL_0044 IL_003e: br.s IL_0048 IL_0040: ldc.i4.1 IL_0041: stloc.1 IL_0042: br.s IL_004c IL_0044: ldc.i4.1 IL_0045: stloc.1 IL_0046: br.s IL_004c IL_0048: ldc.i4.0 IL_0049: stloc.1 IL_004a: br.s IL_004c IL_004c: ldc.i4.1 IL_004d: brtrue.s IL_0050 IL_004f: nop IL_0050: ldloc.1 IL_0051: stloc.3 IL_0052: ldloc.3 IL_0053: ldc.i4.0 IL_0054: cgt.un IL_0056: endfilter } // end filter { // handler IL_0058: pop IL_0059: nop IL_005a: ldloc.0 IL_005b: callvirt ""string System.Exception.Message.get"" IL_0060: newobj ""System.Exception..ctor(string)"" IL_0065: throw } catch object { IL_0066: pop IL_0067: nop IL_0068: nop IL_0069: leave.s IL_006b } IL_006b: ret } "); } else { compVerifier.VerifyIL("C.M(string)", @" { // Code size 89 (0x59) .maxstack 2 .locals init (System.Exception V_0, //e bool V_1, string V_2) .try { IL_0000: ldarg.0 IL_0001: call ""void C.T(string)"" IL_0006: leave.s IL_0058 } filter { IL_0008: isinst ""System.Exception"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_0046 IL_0014: stloc.0 IL_0015: ldloc.0 IL_0016: callvirt ""string System.Exception.Message.get"" IL_001b: stloc.2 IL_001c: ldloc.2 IL_001d: ldstr ""frog"" IL_0022: call ""bool string.op_Equality(string, string)"" IL_0027: brtrue.s IL_0038 IL_0029: ldloc.2 IL_002a: ldstr ""toad"" IL_002f: call ""bool string.op_Equality(string, string)"" IL_0034: brtrue.s IL_003c IL_0036: br.s IL_0040 IL_0038: ldc.i4.1 IL_0039: stloc.1 IL_003a: br.s IL_0042 IL_003c: ldc.i4.1 IL_003d: stloc.1 IL_003e: br.s IL_0042 IL_0040: ldc.i4.0 IL_0041: stloc.1 IL_0042: ldloc.1 IL_0043: ldc.i4.0 IL_0044: cgt.un IL_0046: endfilter } // end filter { // handler IL_0048: pop IL_0049: ldloc.0 IL_004a: callvirt ""string System.Exception.Message.get"" IL_004f: newobj ""System.Exception..ctor(string)"" IL_0054: throw } catch object { IL_0055: pop IL_0056: leave.s IL_0058 } IL_0058: ret } "); } } } [Fact] public void SwitchExpressionAsExceptionFilter_02() { var source = @" using System; class C { public static void Main() { try { throw new Exception(); } catch when ((3 is int i) switch { true when M(() => i) => true, _ => false }) { Console.WriteLine(""correct""); } } static bool M(Func<int> func) { func(); return true; } } "; var expectedOutput = @"correct"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] [WorkItem(48259, "https://github.com/dotnet/roslyn/issues/48259")] public void SwitchExpressionAsExceptionFilter_03() { var source = @" using System; using System.Threading.Tasks; public static class Program { static async Task Main() { Exception ex = new ArgumentException(); try { throw ex; } catch (Exception e) when (e switch { InvalidOperationException => true, _ => false }) { return; } catch (Exception) { Console.WriteLine(""correct""); } } } "; var expectedOutput = "correct"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (7,23): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // static async Task Main() Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(7, 23)); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] [WorkItem(48259, "https://github.com/dotnet/roslyn/issues/48259")] public void SwitchExpressionAsExceptionFilter_04() { var source = @" using System; using System.Threading.Tasks; public static class Program { static async Task Main() { Exception ex = new ArgumentException(); try { throw ex; } catch (Exception e) when (e switch { ArgumentException => true, _ => false }) { Console.WriteLine(""correct""); return; } } } "; var expectedOutput = "correct"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (7,23): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // static async Task Main() Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(7, 23)); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [WorkItem(48563, "https://github.com/dotnet/roslyn/issues/48563")] [Theory] [InlineData("void*")] [InlineData("char*")] [InlineData("delegate*<void>")] public void IsNull_01(string pointerType) { var source = $@"using static System.Console; unsafe class Program {{ static void Main() {{ Check(0); Check(-1); }} static void Check(nint i) {{ {pointerType} p = ({pointerType})i; WriteLine(EqualNull(p)); WriteLine(IsNull(p)); WriteLine(NotEqualNull(p)); WriteLine(IsNotNull(p)); }} static bool EqualNull({pointerType} p) => p == null; static bool NotEqualNull({pointerType} p) => p != null; static bool IsNull({pointerType} p) => p is null; static bool IsNotNull({pointerType} p) => p is not null; }}"; var verifier = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: @"True True False False False False True True"); string expectedEqualNull = @"{ // Code size 6 (0x6) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: conv.u IL_0003: ceq IL_0005: ret }"; string expectedNotEqualNull = @"{ // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: conv.u IL_0003: ceq IL_0005: ldc.i4.0 IL_0006: ceq IL_0008: ret }"; verifier.VerifyIL("Program.EqualNull", expectedEqualNull); verifier.VerifyIL("Program.NotEqualNull", expectedNotEqualNull); verifier.VerifyIL("Program.IsNull", expectedEqualNull); verifier.VerifyIL("Program.IsNotNull", expectedNotEqualNull); } [WorkItem(48563, "https://github.com/dotnet/roslyn/issues/48563")] [Fact] public void IsNull_02() { var source = @"using static System.Console; unsafe class Program { static void Main() { Check(0); Check(-1); } static void Check(nint i) { char* p = (char*)i; WriteLine(EqualNull(p)); } static bool EqualNull(char* p) => p switch { null => true, _ => false }; }"; var verifier = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: @"True False"); verifier.VerifyIL("Program.EqualNull", @"{ // Code size 13 (0xd) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: conv.u IL_0003: bne.un.s IL_0009 IL_0005: ldc.i4.1 IL_0006: stloc.0 IL_0007: br.s IL_000b IL_0009: ldc.i4.0 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ret }"); } [WorkItem(48563, "https://github.com/dotnet/roslyn/issues/48563")] [Fact] public void IsNull_03() { var source = @"using static System.Console; unsafe class C { public char* P; } unsafe class Program { static void Main() { Check(0); Check(-1); } static void Check(nint i) { char* p = (char*)i; WriteLine(EqualNull(new C() { P = p })); } static bool EqualNull(C c) => c switch { { P: null } => true, _ => false }; }"; var verifier = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: @"True False"); verifier.VerifyIL("Program.EqualNull", @"{ // Code size 21 (0x15) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0011 IL_0003: ldarg.0 IL_0004: ldfld ""char* C.P"" IL_0009: ldc.i4.0 IL_000a: conv.u IL_000b: bne.un.s IL_0011 IL_000d: ldc.i4.1 IL_000e: stloc.0 IL_000f: br.s IL_0013 IL_0011: ldc.i4.0 IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ret }"); } #endregion Miscellaneous #region Target Typed Switch [Fact] public void TargetTypedSwitch_Assignment() { var source = @" using System; class Program { public static void Main() { Console.Write(M(false)); Console.Write(M(true)); } static object M(bool b) { int result = b switch { false => new A(), true => new B() }; return result; } } class A { public static implicit operator int(A a) => throw null; public static implicit operator B(A a) => new B(); } class B { public static implicit operator int(B b) => (b == null) ? throw null : 2; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"22"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void TargetTypedSwitch_Return() { var source = @" using System; class Program { public static void Main() { Console.Write(M(false)); Console.Write(M(true)); } static long M(bool b) { return b switch { false => new A(), true => new B() }; } } class A { public static implicit operator int(A a) => throw null; public static implicit operator B(A a) => new B(); } class B { public static implicit operator int(B b) => (b == null) ? throw null : 2; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"22"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void TargetTypedSwitch_Argument_01() { var source = @" using System; class Program { public static void Main() { Console.Write(M1(false)); Console.Write(M1(true)); } static object M1(bool b) { return M2(b switch { false => new A(), true => new B() }); } static Exception M2(Exception ex) => ex; static int M2(int i) => i; static int M2(string s) => s.Length; } class A : Exception { public static implicit operator int(A a) => throw null; public static implicit operator B(A a) => throw null; } class B : Exception { public static implicit operator int(B b) => throw null; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (12,16): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M2(Exception)' and 'Program.M2(int)' // return M2(b switch { false => new A(), true => new B() }); Diagnostic(ErrorCode.ERR_AmbigCall, "M2").WithArguments("Program.M2(System.Exception)", "Program.M2(int)").WithLocation(12, 16) ); } [Fact] public void TargetTypedSwitch_Argument_02() { var source = @" using System; class Program { public static void Main() { Console.Write(M1(false)); Console.Write(M1(true)); } static object M1(bool b) { return M2(b switch { false => new A(), true => new B() }); } // static Exception M2(Exception ex) => ex; static int M2(int i) => i; static int M2(string s) => s.Length; } class A : Exception { public static implicit operator int(A a) => throw null; public static implicit operator B(A a) => new B(); } class B : Exception { public static implicit operator int(B b) => (b == null) ? throw null : 2; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"22"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void TargetTypedSwitch_Arglist() { var source = @" using System; class Program { public static void Main() { Console.WriteLine(M1(false)); Console.WriteLine(M1(true)); } static object M1(bool b) { return M2(__arglist(b switch { false => new A(), true => new B() })); } static int M2(__arglist) => 1; } class A { public A() { Console.Write(""new A; ""); } public static implicit operator B(A a) { Console.Write(""A->""); return new B(); } } class B { public B() { Console.Write(""new B; ""); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"new A; A->new B; 1 new B; 1"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void TargetTypedSwitch_StackallocSize() { var source = @" using System; class Program { public static void Main() { M1(false); M1(true); } static void M1(bool b) { Span<int> s = stackalloc int[b switch { false => new A(), true => new B() }]; Console.WriteLine(s.Length); } } class A { public A() { Console.Write(""new A; ""); } public static implicit operator int(A a) { Console.Write(""A->int; ""); return 4; } } class B { public B() { Console.Write(""new B; ""); } public static implicit operator int(B b) { Console.Write(""B->int; ""); return 2; } } "; var compilation = CreateCompilationWithMscorlibAndSpan(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"new A; A->int; 4 new B; B->int; 2"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped); } [Fact] public void TargetTypedSwitch_Attribute() { var source = @" using System; class Program { [My(1 switch { 1 => 1, _ => 2 })] public static void M1() { } [My(1 switch { 1 => new A(), _ => new B() })] public static void M2() { } [My(1 switch { 1 => 1, _ => string.Empty })] public static void M3() { } } public class MyAttribute : Attribute { public MyAttribute(int Value) { } } public class A { public static implicit operator int(A a) => 4; } public class B { public static implicit operator int(B b) => 2; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (5,9): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(1 switch { 1 => 1, _ => 2 })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => 1, _ => 2 }").WithLocation(5, 9), // (8,9): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(1 switch { 1 => new A(), _ => new B() })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => new A(), _ => new B() }").WithLocation(8, 9), // (11,9): error CS1503: Argument 1: cannot convert from '<switch expression>' to 'int' // [My(1 switch { 1 => 1, _ => string.Empty })] Diagnostic(ErrorCode.ERR_BadArgType, "1 switch { 1 => 1, _ => string.Empty }").WithArguments("1", "<switch expression>", "int").WithLocation(11, 9) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var switchExpressions = tree.GetRoot().DescendantNodes().OfType<SwitchExpressionSyntax>().ToArray(); VerifyOperationTreeForNode(compilation, model, switchExpressions[0], @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... 1, _ => 2 }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => 1') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => 2') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') "); VerifyOperationTreeForNode(compilation, model, switchExpressions[1], @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... > new B() }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => new A()') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 A.op_Implicit(A a)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new A()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 A.op_Implicit(A a)) Operand: IObjectCreationOperation (Constructor: A..ctor()) (OperationKind.ObjectCreation, Type: A, IsInvalid) (Syntax: 'new A()') Arguments(0) Initializer: null ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => new B()') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 B.op_Implicit(B b)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new B()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 B.op_Implicit(B b)) Operand: IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B, IsInvalid) (Syntax: 'new B()') Arguments(0) Initializer: null "); VerifyOperationTreeForNode(compilation, model, switchExpressions[2], @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?, IsInvalid) (Syntax: '1 switch { ... ing.Empty }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => 1') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => string.Empty') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsInvalid, IsImplicit) (Syntax: 'string.Empty') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null "); } [Fact] public void TargetTypedSwitch_Attribute_NamedArgument() { var source = @" using System; class Program { [My(Value = 1 switch { 1 => 1, _ => 2 })] public static void M1() { } [My(Value = 1 switch { 1 => new A(), _ => new B() })] public static void M2() { } [My(Value = 1 switch { 1 => 1, _ => string.Empty })] public static void M3() { } } public class MyAttribute : Attribute { public MyAttribute() { } public int Value { get; set; } } public class A { public static implicit operator int(A a) => 4; } public class B { public static implicit operator int(B b) => 2; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (5,17): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(Value = 1 switch { 1 => 1, _ => 2 })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => 1, _ => 2 }").WithLocation(5, 17), // (8,17): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(Value = 1 switch { 1 => new A(), _ => new B() })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => new A(), _ => new B() }").WithLocation(8, 17), // (11,41): error CS0029: Cannot implicitly convert type 'string' to 'int' // [My(Value = 1 switch { 1 => 1, _ => string.Empty })] Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 41) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var attributeArguments = tree.GetRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().ToArray(); VerifyOperationTreeForNode(compilation, model, attributeArguments[0], @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'Value = 1 s ... 1, _ => 2 }') Left: IPropertyReferenceOperation: System.Int32 MyAttribute.Value { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Value') Instance Receiver: null Right: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... 1, _ => 2 }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => 1') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => 2') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') "); VerifyOperationTreeForNode(compilation, model, attributeArguments[1], @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'Value = 1 s ... > new B() }') Left: IPropertyReferenceOperation: System.Int32 MyAttribute.Value { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Value') Instance Receiver: null Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '1 switch { ... > new B() }') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... > new B() }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => new A()') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 A.op_Implicit(A a)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new A()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 A.op_Implicit(A a)) Operand: IObjectCreationOperation (Constructor: A..ctor()) (OperationKind.ObjectCreation, Type: A, IsInvalid) (Syntax: 'new A()') Arguments(0) Initializer: null ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => new B()') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 B.op_Implicit(B b)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new B()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 B.op_Implicit(B b)) Operand: IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B, IsInvalid) (Syntax: 'new B()') Arguments(0) Initializer: null "); VerifyOperationTreeForNode(compilation, model, attributeArguments[2], @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'Value = 1 s ... ing.Empty }') Left: IPropertyReferenceOperation: System.Int32 MyAttribute.Value { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Value') Instance Receiver: null Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '1 switch { ... ing.Empty }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?, IsInvalid) (Syntax: '1 switch { ... ing.Empty }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 1') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => string.Empty') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsInvalid, IsImplicit) (Syntax: 'string.Empty') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null "); } [Fact] public void TargetTypedSwitch_Attribute_MissingNamedArgument() { var source = @" using System; class Program { [My(Value = 1 switch { 1 => 1, _ => 2 })] public static void M1() { } [My(Value = 1 switch { 1 => new A(), _ => new B() })] public static void M2() { } [My(Value = 1 switch { 1 => 1, _ => string.Empty })] public static void M3() { } } public class MyAttribute : Attribute { public MyAttribute() { } } public class A { public static implicit operator int(A a) => 4; } public class B { public static implicit operator int(B b) => 2; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (5,9): error CS0246: The type or namespace name 'Value' could not be found (are you missing a using directive or an assembly reference?) // [My(Value = 1 switch { 1 => 1, _ => 2 })] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Value").WithArguments("Value").WithLocation(5, 9), // (8,9): error CS0246: The type or namespace name 'Value' could not be found (are you missing a using directive or an assembly reference?) // [My(Value = 1 switch { 1 => new A(), _ => new B() })] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Value").WithArguments("Value").WithLocation(8, 9), // (11,9): error CS0246: The type or namespace name 'Value' could not be found (are you missing a using directive or an assembly reference?) // [My(Value = 1 switch { 1 => 1, _ => string.Empty })] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Value").WithArguments("Value").WithLocation(11, 9) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var attributeArguments = tree.GetRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().ToArray(); VerifyOperationTreeForNode(compilation, model, attributeArguments[0], @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Value = 1 s ... 1, _ => 2 }') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Value') Children(0) Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1 switch { ... 1, _ => 2 }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32) (Syntax: '1 switch { ... 1, _ => 2 }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 1') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => 2') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "); VerifyOperationTreeForNode(compilation, model, attributeArguments[1], @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Value = 1 s ... > new B() }') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Value') Children(0) Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1 switch { ... > new B() }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?) (Syntax: '1 switch { ... > new B() }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => new A()') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: 'new A()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IObjectCreationOperation (Constructor: A..ctor()) (OperationKind.ObjectCreation, Type: A) (Syntax: 'new A()') Arguments(0) Initializer: null ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => new B()') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: 'new B()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B) (Syntax: 'new B()') Arguments(0) Initializer: null "); VerifyOperationTreeForNode(compilation, model, attributeArguments[2], @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Value = 1 s ... ing.Empty }') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Value') Children(0) Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1 switch { ... ing.Empty }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?) (Syntax: '1 switch { ... ing.Empty }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 1') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => string.Empty') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: 'string.Empty') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "); } [Fact] public void TargetTypedSwitch_As() { var source = @" class Program { public static void M(int i, string s) { // we do not target-type the left-hand-side of an as expression _ = i switch { 1 => i, _ => s } as object; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,15): error CS8506: No best type was found for the switch expression. // _ = i switch { 1 => i, _ => s } as object; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(7, 15) ); } [Fact] public void TargetTypedSwitch_DoubleConversion() { var source = @"using System; class Program { public static void Main(string[] args) { M(false); M(true); } public static void M(bool b) { C c = b switch { false => new A(), true => new B() }; Console.WriteLine("".""); } } class A { public A() { Console.Write(""new A; ""); } public static implicit operator B(A a) { Console.Write(""A->""); return new B(); } } class B { public B() { Console.Write(""new B; ""); } public static implicit operator C(B a) { Console.Write(""B->""); return new C(); } } class C { public C() { Console.Write(""new C; ""); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"new A; A->new B; B->new C; . new B; B->new C; ."; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void TargetTypedSwitch_StringInsert() { var source = @" using System; class Program { public static void Main() { Console.Write($""{false switch { false => new A(), true => new B() }}""); Console.Write($""{true switch { false => new A(), true => new B() }}""); } } class A { } class B { } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "AB"); } #endregion Target Typed Switch #region Pattern Combinators [Fact] public void IsPatternDisjunct_01() { var source = @" using System; class C { static bool M1(object o) => o is int or long; static bool M2(object o) => o is int || o is long; public static void Main() { Console.Write(M1(1)); Console.Write(M1(string.Empty)); Console.Write(M1(1L)); Console.Write(M1(1UL)); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); var expectedOutput = @"TrueFalseTrueFalse"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); var code = @" { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.0 IL_0001: isinst ""int"" IL_0006: brtrue.s IL_0013 IL_0008: ldarg.0 IL_0009: isinst ""long"" IL_000e: ldnull IL_000f: cgt.un IL_0011: br.s IL_0014 IL_0013: ldc.i4.1 IL_0014: ret } "; compVerifier.VerifyIL("C.M1", code); compVerifier.VerifyIL("C.M2", code); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); code = @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: isinst ""int"" IL_0006: brtrue.s IL_0012 IL_0008: ldarg.0 IL_0009: isinst ""long"" IL_000e: ldnull IL_000f: cgt.un IL_0011: ret IL_0012: ldc.i4.1 IL_0013: ret } "; compVerifier.VerifyIL("C.M1", code); compVerifier.VerifyIL("C.M2", code); } [Fact] public void IsPatternDisjunct_02() { var source = @" using System; class C { static string M1(object o) => (o is int or long) ? ""True"" : ""False""; static string M2(object o) => (o is int || o is long) ? ""True"" : ""False""; public static void Main() { Console.Write(M1(1)); Console.Write(M1(string.Empty)); Console.Write(M1(1L)); Console.Write(M1(1UL)); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); var expectedOutput = @"TrueFalseTrueFalse"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); var code = @" { // Code size 29 (0x1d) .maxstack 1 IL_0000: ldarg.0 IL_0001: isinst ""int"" IL_0006: brtrue.s IL_0017 IL_0008: ldarg.0 IL_0009: isinst ""long"" IL_000e: brtrue.s IL_0017 IL_0010: ldstr ""False"" IL_0015: br.s IL_001c IL_0017: ldstr ""True"" IL_001c: ret } "; compVerifier.VerifyIL("C.M1", code); compVerifier.VerifyIL("C.M2", code); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); code = @" { // Code size 28 (0x1c) .maxstack 1 IL_0000: ldarg.0 IL_0001: isinst ""int"" IL_0006: brtrue.s IL_0016 IL_0008: ldarg.0 IL_0009: isinst ""long"" IL_000e: brtrue.s IL_0016 IL_0010: ldstr ""False"" IL_0015: ret IL_0016: ldstr ""True"" IL_001b: ret } "; compVerifier.VerifyIL("C.M1", code); compVerifier.VerifyIL("C.M2", code); } [Fact] public void IsPatternDisjunct_03() { var source = @" using System; class C { static bool M1(object o) => o is >= 'A' and <= 'Z' or >= 'a' and <= 'z'; static bool M2(object o) => o is char c && (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'); public static void Main() { Console.Write(M1('A')); Console.Write(M1('0')); Console.Write(M1('q')); Console.Write(M1(2)); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); var expectedOutput = @"TrueFalseTrueFalse"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (char V_0, bool V_1) IL_0000: ldarg.0 IL_0001: isinst ""char"" IL_0006: brfalse.s IL_002b IL_0008: ldarg.0 IL_0009: unbox.any ""char"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: ldc.i4.s 97 IL_0012: blt.s IL_001b IL_0014: ldloc.0 IL_0015: ldc.i4.s 122 IL_0017: ble.s IL_0027 IL_0019: br.s IL_002b IL_001b: ldloc.0 IL_001c: ldc.i4.s 65 IL_001e: blt.s IL_002b IL_0020: ldloc.0 IL_0021: ldc.i4.s 90 IL_0023: ble.s IL_0027 IL_0025: br.s IL_002b IL_0027: ldc.i4.1 IL_0028: stloc.1 IL_0029: br.s IL_002d IL_002b: ldc.i4.0 IL_002c: stloc.1 IL_002d: ldloc.1 IL_002e: ret } "); compVerifier.VerifyIL("C.M2", @" { // Code size 48 (0x30) .maxstack 2 .locals init (char V_0) //c IL_0000: ldarg.0 IL_0001: isinst ""char"" IL_0006: brfalse.s IL_002e IL_0008: ldarg.0 IL_0009: unbox.any ""char"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: ldc.i4.s 65 IL_0012: blt.s IL_0019 IL_0014: ldloc.0 IL_0015: ldc.i4.s 90 IL_0017: ble.s IL_002b IL_0019: ldloc.0 IL_001a: ldc.i4.s 97 IL_001c: blt.s IL_0028 IL_001e: ldloc.0 IL_001f: ldc.i4.s 122 IL_0021: cgt IL_0023: ldc.i4.0 IL_0024: ceq IL_0026: br.s IL_0029 IL_0028: ldc.i4.0 IL_0029: br.s IL_002c IL_002b: ldc.i4.1 IL_002c: br.s IL_002f IL_002e: ldc.i4.0 IL_002f: ret } "); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @" { // Code size 45 (0x2d) .maxstack 2 .locals init (char V_0, bool V_1) IL_0000: ldarg.0 IL_0001: isinst ""char"" IL_0006: brfalse.s IL_0029 IL_0008: ldarg.0 IL_0009: unbox.any ""char"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: ldc.i4.s 97 IL_0012: blt.s IL_001b IL_0014: ldloc.0 IL_0015: ldc.i4.s 122 IL_0017: ble.s IL_0025 IL_0019: br.s IL_0029 IL_001b: ldloc.0 IL_001c: ldc.i4.s 65 IL_001e: blt.s IL_0029 IL_0020: ldloc.0 IL_0021: ldc.i4.s 90 IL_0023: bgt.s IL_0029 IL_0025: ldc.i4.1 IL_0026: stloc.1 IL_0027: br.s IL_002b IL_0029: ldc.i4.0 IL_002a: stloc.1 IL_002b: ldloc.1 IL_002c: ret } "); compVerifier.VerifyIL("C.M2", @" { // Code size 45 (0x2d) .maxstack 2 .locals init (char V_0) //c IL_0000: ldarg.0 IL_0001: isinst ""char"" IL_0006: brfalse.s IL_002b IL_0008: ldarg.0 IL_0009: unbox.any ""char"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: ldc.i4.s 65 IL_0012: blt.s IL_0019 IL_0014: ldloc.0 IL_0015: ldc.i4.s 90 IL_0017: ble.s IL_0029 IL_0019: ldloc.0 IL_001a: ldc.i4.s 97 IL_001c: blt.s IL_0027 IL_001e: ldloc.0 IL_001f: ldc.i4.s 122 IL_0021: cgt IL_0023: ldc.i4.0 IL_0024: ceq IL_0026: ret IL_0027: ldc.i4.0 IL_0028: ret IL_0029: ldc.i4.1 IL_002a: ret IL_002b: ldc.i4.0 IL_002c: ret } "); } [Fact] public void IsPatternDisjunct_04() { var source = @" using System; class C { static int M1(char c) => (c is >= 'A' and <= 'Z' or >= 'a' and <= 'z') ? 1 : 0; static int M2(char c) => (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') ? 1 : 0; public static void Main() { Console.Write(M1('A')); Console.Write(M1('0')); Console.Write(M1('q')); Console.Write(M1(' ')); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); var expectedOutput = @"1010"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @" { // Code size 38 (0x26) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.s 97 IL_0003: blt.s IL_000c IL_0005: ldarg.0 IL_0006: ldc.i4.s 122 IL_0008: ble.s IL_0018 IL_000a: br.s IL_001c IL_000c: ldarg.0 IL_000d: ldc.i4.s 65 IL_000f: blt.s IL_001c IL_0011: ldarg.0 IL_0012: ldc.i4.s 90 IL_0014: ble.s IL_0018 IL_0016: br.s IL_001c IL_0018: ldc.i4.1 IL_0019: stloc.0 IL_001a: br.s IL_001e IL_001c: ldc.i4.0 IL_001d: stloc.0 IL_001e: ldloc.0 IL_001f: brtrue.s IL_0024 IL_0021: ldc.i4.0 IL_0022: br.s IL_0025 IL_0024: ldc.i4.1 IL_0025: ret } "); compVerifier.VerifyIL("C.M2", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 65 IL_0003: blt.s IL_000a IL_0005: ldarg.0 IL_0006: ldc.i4.s 90 IL_0008: ble.s IL_0017 IL_000a: ldarg.0 IL_000b: ldc.i4.s 97 IL_000d: blt.s IL_0014 IL_000f: ldarg.0 IL_0010: ldc.i4.s 122 IL_0012: ble.s IL_0017 IL_0014: ldc.i4.0 IL_0015: br.s IL_0018 IL_0017: ldc.i4.1 IL_0018: ret } "); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @" { // Code size 35 (0x23) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.s 97 IL_0003: blt.s IL_000c IL_0005: ldarg.0 IL_0006: ldc.i4.s 122 IL_0008: ble.s IL_0016 IL_000a: br.s IL_001a IL_000c: ldarg.0 IL_000d: ldc.i4.s 65 IL_000f: blt.s IL_001a IL_0011: ldarg.0 IL_0012: ldc.i4.s 90 IL_0014: bgt.s IL_001a IL_0016: ldc.i4.1 IL_0017: stloc.0 IL_0018: br.s IL_001c IL_001a: ldc.i4.0 IL_001b: stloc.0 IL_001c: ldloc.0 IL_001d: brtrue.s IL_0021 IL_001f: ldc.i4.0 IL_0020: ret IL_0021: ldc.i4.1 IL_0022: ret } "); compVerifier.VerifyIL("C.M2", @" { // Code size 24 (0x18) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 65 IL_0003: blt.s IL_000a IL_0005: ldarg.0 IL_0006: ldc.i4.s 90 IL_0008: ble.s IL_0016 IL_000a: ldarg.0 IL_000b: ldc.i4.s 97 IL_000d: blt.s IL_0014 IL_000f: ldarg.0 IL_0010: ldc.i4.s 122 IL_0012: ble.s IL_0016 IL_0014: ldc.i4.0 IL_0015: ret IL_0016: ldc.i4.1 IL_0017: ret } "); } [Fact] public void IsPatternDisjunct_05() { var source = @" using System; class C { static int M1(char c) { if (c is >= 'A' and <= 'Z' or >= 'a' and <= 'z') return 1; else return 0; } static int M2(char c) { if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') return 1; else return 0; } public static void Main() { Console.Write(M1('A')); Console.Write(M1('0')); Console.Write(M1('q')); Console.Write(M1(' ')); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); var expectedOutput = @"1010"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (bool V_0, bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.s 97 IL_0004: blt.s IL_000d IL_0006: ldarg.0 IL_0007: ldc.i4.s 122 IL_0009: ble.s IL_0019 IL_000b: br.s IL_001d IL_000d: ldarg.0 IL_000e: ldc.i4.s 65 IL_0010: blt.s IL_001d IL_0012: ldarg.0 IL_0013: ldc.i4.s 90 IL_0015: ble.s IL_0019 IL_0017: br.s IL_001d IL_0019: ldc.i4.1 IL_001a: stloc.0 IL_001b: br.s IL_001f IL_001d: ldc.i4.0 IL_001e: stloc.0 IL_001f: ldloc.0 IL_0020: stloc.1 IL_0021: ldloc.1 IL_0022: brfalse.s IL_0028 IL_0024: ldc.i4.1 IL_0025: stloc.2 IL_0026: br.s IL_002c IL_0028: ldc.i4.0 IL_0029: stloc.2 IL_002a: br.s IL_002c IL_002c: ldloc.2 IL_002d: ret } "); compVerifier.VerifyIL("C.M2", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (bool V_0, int V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.s 65 IL_0004: blt.s IL_000b IL_0006: ldarg.0 IL_0007: ldc.i4.s 90 IL_0009: ble.s IL_001d IL_000b: ldarg.0 IL_000c: ldc.i4.s 97 IL_000e: blt.s IL_001a IL_0010: ldarg.0 IL_0011: ldc.i4.s 122 IL_0013: cgt IL_0015: ldc.i4.0 IL_0016: ceq IL_0018: br.s IL_001b IL_001a: ldc.i4.0 IL_001b: br.s IL_001e IL_001d: ldc.i4.1 IL_001e: stloc.0 IL_001f: ldloc.0 IL_0020: brfalse.s IL_0026 IL_0022: ldc.i4.1 IL_0023: stloc.1 IL_0024: br.s IL_002a IL_0026: ldc.i4.0 IL_0027: stloc.1 IL_0028: br.s IL_002a IL_002a: ldloc.1 IL_002b: ret } "); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @" { // Code size 35 (0x23) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.s 97 IL_0003: blt.s IL_000c IL_0005: ldarg.0 IL_0006: ldc.i4.s 122 IL_0008: ble.s IL_0016 IL_000a: br.s IL_001a IL_000c: ldarg.0 IL_000d: ldc.i4.s 65 IL_000f: blt.s IL_001a IL_0011: ldarg.0 IL_0012: ldc.i4.s 90 IL_0014: bgt.s IL_001a IL_0016: ldc.i4.1 IL_0017: stloc.0 IL_0018: br.s IL_001c IL_001a: ldc.i4.0 IL_001b: stloc.0 IL_001c: ldloc.0 IL_001d: brfalse.s IL_0021 IL_001f: ldc.i4.1 IL_0020: ret IL_0021: ldc.i4.0 IL_0022: ret } "); compVerifier.VerifyIL("C.M2", @" { // Code size 24 (0x18) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 65 IL_0003: blt.s IL_000a IL_0005: ldarg.0 IL_0006: ldc.i4.s 90 IL_0008: ble.s IL_0014 IL_000a: ldarg.0 IL_000b: ldc.i4.s 97 IL_000d: blt.s IL_0016 IL_000f: ldarg.0 IL_0010: ldc.i4.s 122 IL_0012: bgt.s IL_0016 IL_0014: ldc.i4.1 IL_0015: ret IL_0016: ldc.i4.0 IL_0017: ret } "); } [Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")] public void MultiplePathsToNode_SwitchDispatch_01() { var source = @" using System; class Program { static void Main() { Console.Write(M("""", 0)); // 0 Console.Write(M("""", 1)); // 1 Console.Write(M("""", 2)); // 2 Console.Write(M("""", 3)); // 3 Console.Write(M(""a"", 2)); // 2 Console.Write(M(""a"", 10)); // 3 } static int M(string x, int y) { return (x, y) switch { ("""", 0) => 0, ("""", 1) => 1, (_, 2) => 2, _ => 3 }; } } "; var verifier = CompileAndVerify(source, expectedOutput: "012323", options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); verifier.VerifyIL("Program.M", @"{ // Code size 70 (0x46) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: ldstr """" IL_000b: call ""bool string.op_Equality(string, string)"" IL_0010: brfalse.s IL_0026 IL_0012: ldarg.1 IL_0013: switch ( IL_002c, IL_0030, IL_0034) IL_0024: br.s IL_0038 IL_0026: ldarg.1 IL_0027: ldc.i4.2 IL_0028: beq.s IL_0034 IL_002a: br.s IL_0038 IL_002c: ldc.i4.0 IL_002d: stloc.0 IL_002e: br.s IL_003c IL_0030: ldc.i4.1 IL_0031: stloc.0 IL_0032: br.s IL_003c IL_0034: ldc.i4.2 IL_0035: stloc.0 IL_0036: br.s IL_003c IL_0038: ldc.i4.3 IL_0039: stloc.0 IL_003a: br.s IL_003c IL_003c: ldc.i4.1 IL_003d: brtrue.s IL_0040 IL_003f: nop IL_0040: ldloc.0 IL_0041: stloc.1 IL_0042: br.s IL_0044 IL_0044: ldloc.1 IL_0045: ret }"); } [Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")] public void MultiplePathsToNode_SwitchDispatch_02() { var source = @" using System; class Program { static void Main() { Console.Write(M0("""", 0)); // 0 Console.Write(M0("""", 1)); // 1 Console.Write(M0("""", 2)); // 2 Console.Write(M0("""", 3)); // 3 Console.Write(M0(""a"", 2)); // 2 Console.Write(M0(""a"", 10)); // 3 } static int M0(string x, int y) { return (x, y) switch { ("""", 0) => M1(0), ("""", 1) => M1(1), (_, 2) => M1(2), _ => M1(3) }; } static int M1(int z) { Console.Write(' '); return z; } } "; var verifier = CompileAndVerify(source, expectedOutput: " 0 1 2 3 2 3", options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); verifier.VerifyIL("Program.M0", @"{ // Code size 90 (0x5a) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: ldstr """" IL_000b: call ""bool string.op_Equality(string, string)"" IL_0010: brfalse.s IL_0026 IL_0012: ldarg.1 IL_0013: switch ( IL_002c, IL_0035, IL_003e) IL_0024: br.s IL_0047 IL_0026: ldarg.1 IL_0027: ldc.i4.2 IL_0028: beq.s IL_003e IL_002a: br.s IL_0047 IL_002c: ldc.i4.0 IL_002d: call ""int Program.M1(int)"" IL_0032: stloc.0 IL_0033: br.s IL_0050 IL_0035: ldc.i4.1 IL_0036: call ""int Program.M1(int)"" IL_003b: stloc.0 IL_003c: br.s IL_0050 IL_003e: ldc.i4.2 IL_003f: call ""int Program.M1(int)"" IL_0044: stloc.0 IL_0045: br.s IL_0050 IL_0047: ldc.i4.3 IL_0048: call ""int Program.M1(int)"" IL_004d: stloc.0 IL_004e: br.s IL_0050 IL_0050: ldc.i4.1 IL_0051: brtrue.s IL_0054 IL_0053: nop IL_0054: ldloc.0 IL_0055: stloc.1 IL_0056: br.s IL_0058 IL_0058: ldloc.1 IL_0059: ret }"); } [Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")] public void MultiplePathsToNode_SwitchDispatch_03() { var source = @" using System; class Program { static void Main() { Console.Write(M("""", 0)); // 0 Console.Write(M("""", 1)); // 1 Console.Write(M("""", 2)); // 2 Console.Write(M("""", 3)); // 3 Console.Write(M("""", 4)); // 4 Console.Write(M("""", 5)); // 5 Console.Write(M(""a"", 2)); // 2 Console.Write(M(""a"", 3)); // 3 Console.Write(M(""a"", 4)); // 4 Console.Write(M(""a"", 10)); // 5 } static int M(string x, int y) { return (x, y) switch { ("""", 0) => 0, ("""", 1) => 1, (_, 2) => 2, (_, 3) => 3, (_, 4) => 4, _ => 5 }; } } "; var verifier = CompileAndVerify(source, expectedOutput: "0123452345", options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); verifier.VerifyIL("Program.M", @"{ // Code size 98 (0x62) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: ldstr """" IL_000b: call ""bool string.op_Equality(string, string)"" IL_0010: brfalse.s IL_002e IL_0012: ldarg.1 IL_0013: switch ( IL_0040, IL_0044, IL_0048, IL_004c, IL_0050) IL_002c: br.s IL_0054 IL_002e: ldarg.1 IL_002f: ldc.i4.2 IL_0030: beq.s IL_0048 IL_0032: br.s IL_0034 IL_0034: ldarg.1 IL_0035: ldc.i4.3 IL_0036: beq.s IL_004c IL_0038: br.s IL_003a IL_003a: ldarg.1 IL_003b: ldc.i4.4 IL_003c: beq.s IL_0050 IL_003e: br.s IL_0054 IL_0040: ldc.i4.0 IL_0041: stloc.0 IL_0042: br.s IL_0058 IL_0044: ldc.i4.1 IL_0045: stloc.0 IL_0046: br.s IL_0058 IL_0048: ldc.i4.2 IL_0049: stloc.0 IL_004a: br.s IL_0058 IL_004c: ldc.i4.3 IL_004d: stloc.0 IL_004e: br.s IL_0058 IL_0050: ldc.i4.4 IL_0051: stloc.0 IL_0052: br.s IL_0058 IL_0054: ldc.i4.5 IL_0055: stloc.0 IL_0056: br.s IL_0058 IL_0058: ldc.i4.1 IL_0059: brtrue.s IL_005c IL_005b: nop IL_005c: ldloc.0 IL_005d: stloc.1 IL_005e: br.s IL_0060 IL_0060: ldloc.1 IL_0061: ret }"); } [Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")] public void MultiplePathsToNode_SwitchDispatch_04() { var source = @" using System; class Program { static void Main() { Console.Write(M(""a"", ""x"")); // 0 Console.Write(M(""a"", ""y"")); // 1 Console.Write(M(""a"", ""z"")); // 2 Console.Write(M(""a"", ""w"")); // 3 Console.Write(M(""b"", ""z"")); // 2 Console.Write(M(""c"", ""z"")); // 3 Console.Write(M(""c"", ""w"")); // 3 } static int M(string x, string y) { return (x, y) switch { (""a"", ""x"") => 0, (""a"", ""y"") => 1, (""a"" or ""b"", ""z"") => 2, _ => 3 }; } } "; var verifier = CompileAndVerify(source, expectedOutput: "0123233", options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); verifier.VerifyDiagnostics(); verifier.VerifyIL("Program.M", @"{ // Code size 115 (0x73) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: ldstr ""a"" IL_000b: call ""bool string.op_Equality(string, string)"" IL_0010: brtrue.s IL_0021 IL_0012: ldarg.0 IL_0013: ldstr ""b"" IL_0018: call ""bool string.op_Equality(string, string)"" IL_001d: brtrue.s IL_004a IL_001f: br.s IL_0065 IL_0021: ldarg.1 IL_0022: ldstr ""z"" IL_0027: call ""bool string.op_Equality(string, string)"" IL_002c: brtrue.s IL_0061 IL_002e: ldarg.1 IL_002f: ldstr ""x"" IL_0034: call ""bool string.op_Equality(string, string)"" IL_0039: brtrue.s IL_0059 IL_003b: ldarg.1 IL_003c: ldstr ""y"" IL_0041: call ""bool string.op_Equality(string, string)"" IL_0046: brtrue.s IL_005d IL_0048: br.s IL_0065 IL_004a: ldarg.1 IL_004b: ldstr ""z"" IL_0050: call ""bool string.op_Equality(string, string)"" IL_0055: brtrue.s IL_0061 IL_0057: br.s IL_0065 IL_0059: ldc.i4.0 IL_005a: stloc.0 IL_005b: br.s IL_0069 IL_005d: ldc.i4.1 IL_005e: stloc.0 IL_005f: br.s IL_0069 IL_0061: ldc.i4.2 IL_0062: stloc.0 IL_0063: br.s IL_0069 IL_0065: ldc.i4.3 IL_0066: stloc.0 IL_0067: br.s IL_0069 IL_0069: ldc.i4.1 IL_006a: brtrue.s IL_006d IL_006c: nop IL_006d: ldloc.0 IL_006e: stloc.1 IL_006f: br.s IL_0071 IL_0071: ldloc.1 IL_0072: ret }"); } [Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")] public void MultiplePathsToNode_SwitchDispatch_05() { var source = @" using System; public enum EnumA { A, B, C } public enum EnumB { X, Y, Z } public class Class1 { public string Repro(EnumA a, EnumB b) => (a, b) switch { (EnumA.A, EnumB.X) => ""AX"", (_, EnumB.Y) => ""_Y"", (EnumA.B, EnumB.X) => ""BZ"", (_, EnumB.Z) => ""_Z"", (_, _) => throw new ArgumentException() }; } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugDll); verifier.VerifyDiagnostics(); verifier.VerifyIL("Class1.Repro", @"{ // Code size 90 (0x5a) .maxstack 2 .locals init (string V_0) IL_0000: ldc.i4.1 IL_0001: brtrue.s IL_0004 IL_0003: nop IL_0004: ldarg.1 IL_0005: brtrue.s IL_001b IL_0007: ldarg.2 IL_0008: switch ( IL_002e, IL_0036, IL_0046) IL_0019: br.s IL_004e IL_001b: ldarg.2 IL_001c: ldc.i4.1 IL_001d: beq.s IL_0036 IL_001f: ldarg.1 IL_0020: ldc.i4.1 IL_0021: bne.un.s IL_0028 IL_0023: ldarg.2 IL_0024: brfalse.s IL_003e IL_0026: br.s IL_0028 IL_0028: ldarg.2 IL_0029: ldc.i4.2 IL_002a: beq.s IL_0046 IL_002c: br.s IL_004e IL_002e: ldstr ""AX"" IL_0033: stloc.0 IL_0034: br.s IL_0054 IL_0036: ldstr ""_Y"" IL_003b: stloc.0 IL_003c: br.s IL_0054 IL_003e: ldstr ""BZ"" IL_0043: stloc.0 IL_0044: br.s IL_0054 IL_0046: ldstr ""_Z"" IL_004b: stloc.0 IL_004c: br.s IL_0054 IL_004e: newobj ""System.ArgumentException..ctor()"" IL_0053: throw IL_0054: ldc.i4.1 IL_0055: brtrue.s IL_0058 IL_0057: nop IL_0058: ldloc.0 IL_0059: ret }"); } #endregion Pattern Combinators } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class PatternTests : EmitMetadataTestBase { #region Miscellaneous [Fact, WorkItem(48493, "https://github.com/dotnet/roslyn/issues/48493")] public void Repro_48493() { var source = @" using System; using System.Linq; namespace Sample { internal class Row { public string Message { get; set; } = """"; } internal class Program { private static void Main() { Console.WriteLine(ProcessRow(new Row())); } private static string ProcessRow(Row row) { if (row == null) throw new ArgumentNullException(nameof(row)); return row switch { { Message: ""stringA"" } => ""stringB"", var r when new[] { ""stringC"", ""stringD"" }.Any(x => r.Message.Contains(x)) => ""stringE"", { Message: ""stringF"" } => ""stringG"", _ => ""stringH"", }; } } }"; CompileAndVerify(source, expectedOutput: "stringH"); } [Fact, WorkItem(48493, "https://github.com/dotnet/roslyn/issues/48493")] public void Repro_48493_Simple() { var source = @" using System; internal class Widget { public bool IsGood { get; set; } } internal class Program { private static bool M0(Func<bool> fn) => fn(); private static void Main() { Console.Write(new Widget() switch { { IsGood: true } => 1, _ when M0(() => true) => 2, { } => 3, }); } }"; CompileAndVerify(source, expectedOutput: @"2"); } [Fact, WorkItem(18811, "https://github.com/dotnet/roslyn/issues/18811")] public void MissingNullable_01() { var source = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } static class C { public static bool M() => ((object)123) is int i; } "; var compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseDll); compilation.GetDiagnostics().Verify(); compilation.GetEmitDiagnostics().Verify( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) ); } [Fact, WorkItem(18811, "https://github.com/dotnet/roslyn/issues/18811")] public void MissingNullable_02() { var source = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct Nullable<T> where T : struct { } } static class C { public static bool M() => ((object)123) is int i; } "; var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll); compilation.GetDiagnostics().Verify(); compilation.GetEmitDiagnostics().Verify( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion) ); } [Fact] public void MissingNullable_03() { var source = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct Nullable<T> where T : struct { } } static class C { static void M1(int? x) { switch (x) { case int i: break; } } static bool M2(int? x) => x is int i; } "; var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll); compilation.GetDiagnostics().Verify(); compilation.GetEmitDiagnostics().Verify( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // case int i: break; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(14, 18), // (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // case int i: break; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(14, 18), // (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.get_Value' // case int i: break; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_Value").WithLocation(14, 18), // (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // static bool M2(int? x) => x is int i; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(17, 36), // (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // static bool M2(int? x) => x is int i; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(17, 36), // (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_Value' // static bool M2(int? x) => x is int i; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_Value").WithLocation(17, 36) ); } [Fact] public void MissingNullable_04() { var source = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct Nullable<T> where T : struct { public T GetValueOrDefault() => default(T); } } static class C { static void M1(int? x) { switch (x) { case int i: break; } } static bool M2(int? x) => x is int i; } "; var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll); compilation.GetDiagnostics().Verify(); compilation.GetEmitDiagnostics().Verify( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // case int i: break; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(14, 18), // (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // static bool M2(int? x) => x is int i; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(17, 36) ); } [Fact, WorkItem(17266, "https://github.com/dotnet/roslyn/issues/17266")] public void DoubleEvaluation01() { var source = @"using System; public class C { public static void Main() { if (TryGet() is int index) { Console.WriteLine(index); } } public static int? TryGet() { Console.WriteLine(""eval""); return null; } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"eval"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.Main", @"{ // Code size 42 (0x2a) .maxstack 1 .locals init (int V_0, //index bool V_1, int? V_2) IL_0000: nop IL_0001: call ""int? C.TryGet()"" IL_0006: stloc.2 IL_0007: ldloca.s V_2 IL_0009: call ""bool int?.HasValue.get"" IL_000e: brfalse.s IL_001b IL_0010: ldloca.s V_2 IL_0012: call ""int int?.GetValueOrDefault()"" IL_0017: stloc.0 IL_0018: ldc.i4.1 IL_0019: br.s IL_001c IL_001b: ldc.i4.0 IL_001c: stloc.1 IL_001d: ldloc.1 IL_001e: brfalse.s IL_0029 IL_0020: nop IL_0021: ldloc.0 IL_0022: call ""void System.Console.WriteLine(int)"" IL_0027: nop IL_0028: nop IL_0029: ret }"); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.Main", @"{ // Code size 30 (0x1e) .maxstack 1 .locals init (int V_0, //index int? V_1) IL_0000: call ""int? C.TryGet()"" IL_0005: stloc.1 IL_0006: ldloca.s V_1 IL_0008: call ""bool int?.HasValue.get"" IL_000d: brfalse.s IL_001d IL_000f: ldloca.s V_1 IL_0011: call ""int int?.GetValueOrDefault()"" IL_0016: stloc.0 IL_0017: ldloc.0 IL_0018: call ""void System.Console.WriteLine(int)"" IL_001d: ret }"); } [Fact, WorkItem(19122, "https://github.com/dotnet/roslyn/issues/19122")] public void PatternCrash_01() { var source = @"using System; using System.Collections.Generic; using System.Linq; public class Class2 : IDisposable { public Class2(bool parameter = false) { } public void Dispose() { } } class X<T> { IdentityAccessor<T> idAccessor = new IdentityAccessor<T>(); void Y<U>() where U : T { // BUG: The following line is the problem if (GetT().FirstOrDefault(p => idAccessor.GetId(p) == Guid.Empty) is U u) { } } IEnumerable<T> GetT() { yield return default(T); } } class IdentityAccessor<T> { public Guid GetId(T t) { return Guid.Empty; } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("X<T>.Y<U>", @"{ // Code size 61 (0x3d) .maxstack 3 .locals init (U V_0, //u bool V_1, T V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""System.Collections.Generic.IEnumerable<T> X<T>.GetT()"" IL_0007: ldarg.0 IL_0008: ldftn ""bool X<T>.<Y>b__1_0<U>(T)"" IL_000e: newobj ""System.Func<T, bool>..ctor(object, System.IntPtr)"" IL_0013: call ""T System.Linq.Enumerable.FirstOrDefault<T>(System.Collections.Generic.IEnumerable<T>, System.Func<T, bool>)"" IL_0018: stloc.2 IL_0019: ldloc.2 IL_001a: box ""T"" IL_001f: isinst ""U"" IL_0024: brfalse.s IL_0035 IL_0026: ldloc.2 IL_0027: box ""T"" IL_002c: unbox.any ""U"" IL_0031: stloc.0 IL_0032: ldc.i4.1 IL_0033: br.s IL_0036 IL_0035: ldc.i4.0 IL_0036: stloc.1 IL_0037: ldloc.1 IL_0038: brfalse.s IL_003c IL_003a: nop IL_003b: nop IL_003c: ret }"); } [Fact, WorkItem(24522, "https://github.com/dotnet/roslyn/issues/24522")] public void IgnoreDeclaredConversion_01() { var source = @"class Base<T> { public static implicit operator Derived(Base<T> obj) { return new Derived(); } } class Derived : Base<object> { } class Program { static void Main(string[] args) { Base<object> x = new Derived(); System.Console.WriteLine(x is Derived); System.Console.WriteLine(x is Derived y); switch (x) { case Derived z: System.Console.WriteLine(true); break; } System.Console.WriteLine(null != (x as Derived)); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"True True True True"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("Program.Main", @"{ // Code size 84 (0x54) .maxstack 2 .locals init (Base<object> V_0, //x Derived V_1, //y Derived V_2, //z Base<object> V_3, Base<object> V_4) IL_0000: nop IL_0001: newobj ""Derived..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: isinst ""Derived"" IL_000d: ldnull IL_000e: cgt.un IL_0010: call ""void System.Console.WriteLine(bool)"" IL_0015: nop IL_0016: ldloc.0 IL_0017: isinst ""Derived"" IL_001c: stloc.1 IL_001d: ldloc.1 IL_001e: ldnull IL_001f: cgt.un IL_0021: call ""void System.Console.WriteLine(bool)"" IL_0026: nop IL_0027: ldloc.0 IL_0028: stloc.s V_4 IL_002a: ldloc.s V_4 IL_002c: stloc.3 IL_002d: ldloc.3 IL_002e: isinst ""Derived"" IL_0033: stloc.2 IL_0034: ldloc.2 IL_0035: brtrue.s IL_0039 IL_0037: br.s IL_0044 IL_0039: br.s IL_003b IL_003b: ldc.i4.1 IL_003c: call ""void System.Console.WriteLine(bool)"" IL_0041: nop IL_0042: br.s IL_0044 IL_0044: ldloc.0 IL_0045: isinst ""Derived"" IL_004a: ldnull IL_004b: cgt.un IL_004d: call ""void System.Console.WriteLine(bool)"" IL_0052: nop IL_0053: ret }"); } [Fact] public void DoublePattern01() { var source = @"using System; class Program { static bool P1(double d) => d is double.NaN; static bool P2(float f) => f is float.NaN; static bool P3(double d) => d is 3.14d; static bool P4(float f) => f is 3.14f; static bool P5(object o) { switch (o) { case double.NaN: return true; case float.NaN: return true; case 3.14d: return true; case 3.14f: return true; default: return false; } } public static void Main(string[] args) { Console.Write(P1(double.NaN)); Console.Write(P1(1.0)); Console.Write(P2(float.NaN)); Console.Write(P2(1.0f)); Console.Write(P3(3.14)); Console.Write(P3(double.NaN)); Console.Write(P4(3.14f)); Console.Write(P4(float.NaN)); Console.Write(P5(double.NaN)); Console.Write(P5(0.0d)); Console.Write(P5(float.NaN)); Console.Write(P5(0.0f)); Console.Write(P5(3.14d)); Console.Write(P5(125)); Console.Write(P5(3.14f)); Console.Write(P5(1.0f)); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"TrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalse"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("Program.P1", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""bool double.IsNaN(double)"" IL_0006: ret }"); compVerifier.VerifyIL("Program.P2", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""bool float.IsNaN(float)"" IL_0006: ret }"); compVerifier.VerifyIL("Program.P3", @"{ // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.r8 3.14 IL_000a: ceq IL_000c: ret }"); compVerifier.VerifyIL("Program.P4", @"{ // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.r4 3.14 IL_0006: ceq IL_0008: ret }"); compVerifier.VerifyIL("Program.P5", @"{ // Code size 103 (0x67) .maxstack 2 .locals init (object V_0, double V_1, float V_2, object V_3, bool V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.0 IL_0005: ldloc.0 IL_0006: isinst ""double"" IL_000b: brfalse.s IL_002a IL_000d: ldloc.0 IL_000e: unbox.any ""double"" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: call ""bool double.IsNaN(double)"" IL_001a: brtrue.s IL_004b IL_001c: ldloc.1 IL_001d: ldc.r8 3.14 IL_0026: beq.s IL_0055 IL_0028: br.s IL_005f IL_002a: ldloc.0 IL_002b: isinst ""float"" IL_0030: brfalse.s IL_005f IL_0032: ldloc.0 IL_0033: unbox.any ""float"" IL_0038: stloc.2 IL_0039: ldloc.2 IL_003a: call ""bool float.IsNaN(float)"" IL_003f: brtrue.s IL_0050 IL_0041: ldloc.2 IL_0042: ldc.r4 3.14 IL_0047: beq.s IL_005a IL_0049: br.s IL_005f IL_004b: ldc.i4.1 IL_004c: stloc.s V_4 IL_004e: br.s IL_0064 IL_0050: ldc.i4.1 IL_0051: stloc.s V_4 IL_0053: br.s IL_0064 IL_0055: ldc.i4.1 IL_0056: stloc.s V_4 IL_0058: br.s IL_0064 IL_005a: ldc.i4.1 IL_005b: stloc.s V_4 IL_005d: br.s IL_0064 IL_005f: ldc.i4.0 IL_0060: stloc.s V_4 IL_0062: br.s IL_0064 IL_0064: ldloc.s V_4 IL_0066: ret }"); } [Fact] public void DecimalEquality() { // demonstrate that pattern-matching against a decimal constant is // at least as efficient as simply using == var source = @"using System; public class C { public static void Main() { Console.Write(M1(1.0m)); Console.Write(M2(1.0m)); Console.Write(M1(2.0m)); Console.Write(M2(2.0m)); } static int M1(decimal d) { if (M(d) is 1.0m) return 1; return 0; } static int M2(decimal d) { if (M(d) == 1.0m) return 1; return 0; } public static decimal M(decimal d) { return d; } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"1100"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @"{ // Code size 37 (0x25) .maxstack 6 .locals init (bool V_0, int V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""decimal C.M(decimal)"" IL_0007: ldc.i4.s 10 IL_0009: ldc.i4.0 IL_000a: ldc.i4.0 IL_000b: ldc.i4.0 IL_000c: ldc.i4.1 IL_000d: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0012: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0017: stloc.0 IL_0018: ldloc.0 IL_0019: brfalse.s IL_001f IL_001b: ldc.i4.1 IL_001c: stloc.1 IL_001d: br.s IL_0023 IL_001f: ldc.i4.0 IL_0020: stloc.1 IL_0021: br.s IL_0023 IL_0023: ldloc.1 IL_0024: ret }"); compVerifier.VerifyIL("C.M2", @"{ // Code size 37 (0x25) .maxstack 6 .locals init (bool V_0, int V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""decimal C.M(decimal)"" IL_0007: ldc.i4.s 10 IL_0009: ldc.i4.0 IL_000a: ldc.i4.0 IL_000b: ldc.i4.0 IL_000c: ldc.i4.1 IL_000d: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0012: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0017: stloc.0 IL_0018: ldloc.0 IL_0019: brfalse.s IL_001f IL_001b: ldc.i4.1 IL_001c: stloc.1 IL_001d: br.s IL_0023 IL_001f: ldc.i4.0 IL_0020: stloc.1 IL_0021: br.s IL_0023 IL_0023: ldloc.1 IL_0024: ret }"); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @"{ // Code size 28 (0x1c) .maxstack 6 IL_0000: ldarg.0 IL_0001: call ""decimal C.M(decimal)"" IL_0006: ldc.i4.s 10 IL_0008: ldc.i4.0 IL_0009: ldc.i4.0 IL_000a: ldc.i4.0 IL_000b: ldc.i4.1 IL_000c: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0011: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0016: brfalse.s IL_001a IL_0018: ldc.i4.1 IL_0019: ret IL_001a: ldc.i4.0 IL_001b: ret }"); compVerifier.VerifyIL("C.M2", @"{ // Code size 28 (0x1c) .maxstack 6 IL_0000: ldarg.0 IL_0001: call ""decimal C.M(decimal)"" IL_0006: ldc.i4.s 10 IL_0008: ldc.i4.0 IL_0009: ldc.i4.0 IL_000a: ldc.i4.0 IL_000b: ldc.i4.1 IL_000c: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0011: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0016: brfalse.s IL_001a IL_0018: ldc.i4.1 IL_0019: ret IL_001a: ldc.i4.0 IL_001b: ret }"); } [Fact, WorkItem(16878, "https://github.com/dotnet/roslyn/issues/16878")] public void RedundantNullCheck() { var source = @"public class C { static int M1(bool? b1, bool b2) { switch (b1) { case null: return 1; case var _ when b2: return 2; case true: return 3; case false: return 4; } } static int M2(object o, bool b) { switch (o) { case string a when b: return 1; case string a: return 2; } return 3; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1", @"{ // Code size 35 (0x23) .maxstack 1 .locals init (bool? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool bool?.HasValue.get"" IL_0009: brfalse.s IL_0018 IL_000b: br.s IL_001a IL_000d: ldloca.s V_0 IL_000f: call ""bool bool?.GetValueOrDefault()"" IL_0014: brtrue.s IL_001f IL_0016: br.s IL_0021 IL_0018: ldc.i4.1 IL_0019: ret IL_001a: ldarg.1 IL_001b: brfalse.s IL_000d IL_001d: ldc.i4.2 IL_001e: ret IL_001f: ldc.i4.3 IL_0020: ret IL_0021: ldc.i4.4 IL_0022: ret }"); compVerifier.VerifyIL("C.M2", @"{ // Code size 19 (0x13) .maxstack 1 .locals init (string V_0) //a IL_0000: ldarg.0 IL_0001: isinst ""string"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0011 IL_000a: ldarg.1 IL_000b: brfalse.s IL_000f IL_000d: ldc.i4.1 IL_000e: ret IL_000f: ldc.i4.2 IL_0010: ret IL_0011: ldc.i4.3 IL_0012: ret }"); } [Fact, WorkItem(12813, "https://github.com/dotnet/roslyn/issues/12813")] public void NoBoxingOnIntegerConstantPattern() { var source = @"public class C { static bool M1(int x) { return x is 42; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1", @"{ // Code size 6 (0x6) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: ceq IL_0005: ret }"); } [Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")] public void RefParameter_StoreToTemp() { var source = @"public class C { static bool M1(ref object x) { return x is 42; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1", @"{ // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: ldind.ref IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: isinst ""int"" IL_0009: brfalse.s IL_0016 IL_000b: ldloc.0 IL_000c: unbox.any ""int"" IL_0011: ldc.i4.s 42 IL_0013: ceq IL_0015: ret IL_0016: ldc.i4.0 IL_0017: ret }"); } [Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")] public void RefLocal_StoreToTemp() { var source = @"public class C { static bool M1(bool b, ref object x, ref object y) { ref object z = ref b ? ref x : ref y; return z is 42; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1", @"{ // Code size 30 (0x1e) .maxstack 2 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_0006 IL_0003: ldarg.2 IL_0004: br.s IL_0007 IL_0006: ldarg.1 IL_0007: ldind.ref IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: isinst ""int"" IL_000f: brfalse.s IL_001c IL_0011: ldloc.0 IL_0012: unbox.any ""int"" IL_0017: ldc.i4.s 42 IL_0019: ceq IL_001b: ret IL_001c: ldc.i4.0 IL_001d: ret }"); } [Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")] public void InParameter_StoreToTemp() { var source = @"public class C { static bool M1(in object x) { return x is 42; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1", @"{ // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: ldind.ref IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: isinst ""int"" IL_0009: brfalse.s IL_0016 IL_000b: ldloc.0 IL_000c: unbox.any ""int"" IL_0011: ldc.i4.s 42 IL_0013: ceq IL_0015: ret IL_0016: ldc.i4.0 IL_0017: ret }"); } [Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")] public void RefReadonlyLocal_StoreToTemp() { var source = @"public class C { static bool M1(bool b, in object x, in object y) { ref readonly object z = ref b ? ref x : ref y; return z is 42; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1", @"{ // Code size 30 (0x1e) .maxstack 2 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_0006 IL_0003: ldarg.2 IL_0004: br.s IL_0007 IL_0006: ldarg.1 IL_0007: ldind.ref IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: isinst ""int"" IL_000f: brfalse.s IL_001c IL_0011: ldloc.0 IL_0012: unbox.any ""int"" IL_0017: ldc.i4.s 42 IL_0019: ceq IL_001b: ret IL_001c: ldc.i4.0 IL_001d: ret }"); } [Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")] public void OutParameter_StoreToTemp() { var source = @"public class C { static bool M1(out object x) { x = null; return x is 42; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1", @"{ // Code size 27 (0x1b) .maxstack 2 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: ldnull IL_0002: stind.ref IL_0003: ldarg.0 IL_0004: ldind.ref IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: isinst ""int"" IL_000c: brfalse.s IL_0019 IL_000e: ldloc.0 IL_000f: unbox.any ""int"" IL_0014: ldc.i4.s 42 IL_0016: ceq IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret }"); } [Fact, WorkItem(22654, "https://github.com/dotnet/roslyn/issues/22654")] public void NoRedundantTypeCheck() { var source = @"using System; public class C { public void SwitchBasedPatternMatching(object o) { switch (o) { case int n when n == 1: Console.WriteLine(""1""); break; case string s: Console.WriteLine(""s""); break; case int n when n == 2: Console.WriteLine(""2""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.SwitchBasedPatternMatching", @"{ // Code size 69 (0x45) .maxstack 2 .locals init (int V_0, //n object V_1) IL_0000: ldarg.1 IL_0001: stloc.1 IL_0002: ldloc.1 IL_0003: isinst ""int"" IL_0008: brfalse.s IL_0013 IL_000a: ldloc.1 IL_000b: unbox.any ""int"" IL_0010: stloc.0 IL_0011: br.s IL_001c IL_0013: ldloc.1 IL_0014: isinst ""string"" IL_0019: brtrue.s IL_002b IL_001b: ret IL_001c: ldloc.0 IL_001d: ldc.i4.1 IL_001e: bne.un.s IL_0036 IL_0020: ldstr ""1"" IL_0025: call ""void System.Console.WriteLine(string)"" IL_002a: ret IL_002b: ldstr ""s"" IL_0030: call ""void System.Console.WriteLine(string)"" IL_0035: ret IL_0036: ldloc.0 IL_0037: ldc.i4.2 IL_0038: bne.un.s IL_0044 IL_003a: ldstr ""2"" IL_003f: call ""void System.Console.WriteLine(string)"" IL_0044: ret }"); } [Fact, WorkItem(15437, "https://github.com/dotnet/roslyn/issues/15437")] public void IsTypeDiscard() { var source = @"public class C { public bool IsString(object o) { return o is string _; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.IsString", @"{ // Code size 10 (0xa) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""string"" IL_0006: ldnull IL_0007: cgt.un IL_0009: ret }"); } [Fact, WorkItem(19150, "https://github.com/dotnet/roslyn/issues/19150")] public void RedundantHasValue() { var source = @"using System; public class C { public static void M(int? x) { switch (x) { case int i: Console.Write(i); break; case null: Console.Write(""null""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 33 (0x21) .maxstack 1 IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brfalse.s IL_0016 IL_0009: ldarga.s V_0 IL_000b: call ""int int?.GetValueOrDefault()"" IL_0010: call ""void System.Console.Write(int)"" IL_0015: ret IL_0016: ldstr ""null"" IL_001b: call ""void System.Console.Write(string)"" IL_0020: ret }"); } [Fact, WorkItem(19153, "https://github.com/dotnet/roslyn/issues/19153")] public void RedundantBox() { var source = @"using System; public class C { public static void M<T, U>(U x) where T : U { // when T is not known to be a reference type, there is an unboxing conversion from // a type parameter U to T, provided T depends on U. switch (x) { case T i: Console.Write(i); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M<T, U>(U)", @"{ // Code size 35 (0x23) .maxstack 1 IL_0000: ldarg.0 IL_0001: box ""U"" IL_0006: isinst ""T"" IL_000b: brfalse.s IL_0022 IL_000d: ldarg.0 IL_000e: box ""U"" IL_0013: unbox.any ""T"" IL_0018: box ""T"" IL_001d: call ""void System.Console.Write(object)"" IL_0022: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead01() { var source = @"using System; public class Person { public string Name { get; set; } } public class C { public void M(Person p) { switch (p) { case { Name: ""Bill"" }: Console.WriteLine(""Hey Bill!""); break; case { Name: ""Bob"" }: Console.WriteLine(""Hey Bob!""); break; case { Name: var name }: Console.WriteLine($""Hello {name}!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 82 (0x52) .maxstack 3 .locals init (string V_0) //name IL_0000: ldarg.1 IL_0001: brfalse.s IL_0051 IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldstr ""Bill"" IL_0010: call ""bool string.op_Equality(string, string)"" IL_0015: brtrue.s IL_0026 IL_0017: ldloc.0 IL_0018: ldstr ""Bob"" IL_001d: call ""bool string.op_Equality(string, string)"" IL_0022: brtrue.s IL_0031 IL_0024: br.s IL_003c IL_0026: ldstr ""Hey Bill!"" IL_002b: call ""void System.Console.WriteLine(string)"" IL_0030: ret IL_0031: ldstr ""Hey Bob!"" IL_0036: call ""void System.Console.WriteLine(string)"" IL_003b: ret IL_003c: ldstr ""Hello "" IL_0041: ldloc.0 IL_0042: ldstr ""!"" IL_0047: call ""string string.Concat(string, string, string)"" IL_004c: call ""void System.Console.WriteLine(string)"" IL_0051: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead02() { var source = @"using System; public class Person { public string Name { get; set; } public int Age; } public class C { public void M(Person p) { switch (p) { case Person { Name: var name, Age: 0}: Console.WriteLine($""Hello baby { name }!""); break; case Person { Name: var name }: Console.WriteLine($""Hello { name }!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 64 (0x40) .maxstack 3 .locals init (string V_0, //name string V_1) //name IL_0000: ldarg.1 IL_0001: brfalse.s IL_003f IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: stloc.0 IL_000a: ldarg.1 IL_000b: ldfld ""int Person.Age"" IL_0010: brtrue.s IL_0028 IL_0012: ldstr ""Hello baby "" IL_0017: ldloc.0 IL_0018: ldstr ""!"" IL_001d: call ""string string.Concat(string, string, string)"" IL_0022: call ""void System.Console.WriteLine(string)"" IL_0027: ret IL_0028: ldloc.0 IL_0029: stloc.1 IL_002a: ldstr ""Hello "" IL_002f: ldloc.1 IL_0030: ldstr ""!"" IL_0035: call ""string string.Concat(string, string, string)"" IL_003a: call ""void System.Console.WriteLine(string)"" IL_003f: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead03() { var source = @"using System; public class Person { public string Name { get; set; } } public class Student : Person { } public class C { public void M(Person p) { switch (p) { case { Name: ""Bill"" }: Console.WriteLine(""Hey Bill!""); break; case Student { Name: var name }: Console.WriteLine($""Hello student { name}!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 65 (0x41) .maxstack 3 .locals init (string V_0) //name IL_0000: ldarg.1 IL_0001: brfalse.s IL_0040 IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldstr ""Bill"" IL_0010: call ""bool string.op_Equality(string, string)"" IL_0015: brtrue.s IL_0020 IL_0017: ldarg.1 IL_0018: isinst ""Student"" IL_001d: brtrue.s IL_002b IL_001f: ret IL_0020: ldstr ""Hey Bill!"" IL_0025: call ""void System.Console.WriteLine(string)"" IL_002a: ret IL_002b: ldstr ""Hello student "" IL_0030: ldloc.0 IL_0031: ldstr ""!"" IL_0036: call ""string string.Concat(string, string, string)"" IL_003b: call ""void System.Console.WriteLine(string)"" IL_0040: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead04() { // Cannot combine the evaluations of name here, since we first check if p is Teacher, // and only if that fails check if p is null. // Combining the evaluations would mean first checking if p is null, then evaluating name, then checking if p is Teacher. // This would not necessarily be more performant. var source = @"using System; public class Person { public string Name { get; set; } } public class Teacher : Person { } public class C { public void M(Person p) { switch (p) { case Teacher { Name: var name }: Console.WriteLine($""Hello teacher { name}!""); break; case Person { Name: var name }: Console.WriteLine($""Hello { name}!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 75 (0x4b) .maxstack 3 .locals init (string V_0, //name string V_1) //name IL_0000: ldarg.1 IL_0001: isinst ""Teacher"" IL_0006: brfalse.s IL_0011 IL_0008: ldarg.1 IL_0009: callvirt ""string Person.Name.get"" IL_000e: stloc.0 IL_000f: br.s IL_001d IL_0011: ldarg.1 IL_0012: brfalse.s IL_004a IL_0014: ldarg.1 IL_0015: callvirt ""string Person.Name.get"" IL_001a: stloc.0 IL_001b: br.s IL_0033 IL_001d: ldstr ""Hello teacher "" IL_0022: ldloc.0 IL_0023: ldstr ""!"" IL_0028: call ""string string.Concat(string, string, string)"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ret IL_0033: ldloc.0 IL_0034: stloc.1 IL_0035: ldstr ""Hello "" IL_003a: ldloc.1 IL_003b: ldstr ""!"" IL_0040: call ""string string.Concat(string, string, string)"" IL_0045: call ""void System.Console.WriteLine(string)"" IL_004a: ret } "); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead05() { // Cannot combine the evaluations of name here, since we first check if p is Teacher, // and only if that fails check if p is Student. // Combining the evaluations would mean first checking if p is null, // then evaluating name, // then checking if p is Teacher, // then checking if p is Student. // This would not necessarily be more performant. var source = @"using System; public class Person { public string Name { get; set; } } public class Student : Person { } public class Teacher : Person { } public class C { public void M(Person p) { switch (p) { case Teacher { Name: var name }: Console.WriteLine($""Hello teacher { name}!""); break; case Student { Name: var name }: Console.WriteLine($""Hello student { name}!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 80 (0x50) .maxstack 3 .locals init (string V_0, //name string V_1) //name IL_0000: ldarg.1 IL_0001: isinst ""Teacher"" IL_0006: brfalse.s IL_0011 IL_0008: ldarg.1 IL_0009: callvirt ""string Person.Name.get"" IL_000e: stloc.0 IL_000f: br.s IL_0022 IL_0011: ldarg.1 IL_0012: isinst ""Student"" IL_0017: brfalse.s IL_004f IL_0019: ldarg.1 IL_001a: callvirt ""string Person.Name.get"" IL_001f: stloc.0 IL_0020: br.s IL_0038 IL_0022: ldstr ""Hello teacher "" IL_0027: ldloc.0 IL_0028: ldstr ""!"" IL_002d: call ""string string.Concat(string, string, string)"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret IL_0038: ldloc.0 IL_0039: stloc.1 IL_003a: ldstr ""Hello student "" IL_003f: ldloc.1 IL_0040: ldstr ""!"" IL_0045: call ""string string.Concat(string, string, string)"" IL_004a: call ""void System.Console.WriteLine(string)"" IL_004f: ret } "); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead06() { var source = @"using System; public class Person { public string Name { get; set; } } public class Student : Person { } public class C { public void M(Person p) { switch (p) { case { Name: { Length: 0 } }: Console.WriteLine(""Hello!""); break; case Student { Name: { Length : 1 } }: Console.WriteLine($""Hello student!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 58 (0x3a) .maxstack 2 .locals init (string V_0, int V_1) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0039 IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0039 IL_000d: ldloc.0 IL_000e: callvirt ""int string.Length.get"" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_0024 IL_0017: ldarg.1 IL_0018: isinst ""Student"" IL_001d: brfalse.s IL_0039 IL_001f: ldloc.1 IL_0020: ldc.i4.1 IL_0021: beq.s IL_002f IL_0023: ret IL_0024: ldstr ""Hello!"" IL_0029: call ""void System.Console.WriteLine(string)"" IL_002e: ret IL_002f: ldstr ""Hello student!"" IL_0034: call ""void System.Console.WriteLine(string)"" IL_0039: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead07() { // Cannot combine the evaluations of name here, since we first check if name is MemoryStream, // and only if that fails check if name is null. // Combining the evaluations would mean first checking if name is null, then evaluating name, then checking if p is Teacher. // This would not necessarily be more performant. var source = @"using System; using System.IO; public class Person { public Stream Name { get; set; } } public class C { public void M(Person p) { switch (p) { case Person { Name: MemoryStream { Length: 1 } }: Console.WriteLine(""Your Names A MemoryStream!""); break; case Person { Name: { Length : var x } }: Console.WriteLine(""Your Names A Stream!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 66 (0x42) .maxstack 2 .locals init (System.IO.Stream V_0, System.IO.MemoryStream V_1) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0041 IL_0003: ldarg.1 IL_0004: callvirt ""System.IO.Stream Person.Name.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: isinst ""System.IO.MemoryStream"" IL_0010: stloc.1 IL_0011: ldloc.1 IL_0012: brfalse.s IL_0020 IL_0014: ldloc.1 IL_0015: callvirt ""long System.IO.Stream.Length.get"" IL_001a: ldc.i4.1 IL_001b: conv.i8 IL_001c: beq.s IL_002c IL_001e: br.s IL_0023 IL_0020: ldloc.0 IL_0021: brfalse.s IL_0041 IL_0023: ldloc.0 IL_0024: callvirt ""long System.IO.Stream.Length.get"" IL_0029: pop IL_002a: br.s IL_0037 IL_002c: ldstr ""Your Names A MemoryStream!"" IL_0031: call ""void System.Console.WriteLine(string)"" IL_0036: ret IL_0037: ldstr ""Your Names A Stream!"" IL_003c: call ""void System.Console.WriteLine(string)"" IL_0041: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead08() { var source = @" public class Person { public string Name { get; set; } } public class Student : Person { } public class C { public string M(Person p) { return p switch { { Name: ""Bill"" } => ""Hey Bill!"", Student { Name: var name } => ""Hello student { name}!"", _ => null, }; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 51 (0x33) .maxstack 2 .locals init (string V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_002f IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: ldstr ""Bill"" IL_000e: call ""bool string.op_Equality(string, string)"" IL_0013: brtrue.s IL_001f IL_0015: ldarg.1 IL_0016: isinst ""Student"" IL_001b: brtrue.s IL_0027 IL_001d: br.s IL_002f IL_001f: ldstr ""Hey Bill!"" IL_0024: stloc.0 IL_0025: br.s IL_0031 IL_0027: ldstr ""Hello student { name}!"" IL_002c: stloc.0 IL_002d: br.s IL_0031 IL_002f: ldnull IL_0030: stloc.0 IL_0031: ldloc.0 IL_0032: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead09() { var source = @"using System; public class Person { public virtual string Name { get; set; } } public class Student : Person { } public class C { public void M(Person p) { switch (p) { case { Name: ""Bill"" }: Console.WriteLine(""Hey Bill!""); break; case Student { Name: var name }: Console.WriteLine($""Hello student { name}!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 65 (0x41) .maxstack 3 .locals init (string V_0) //name IL_0000: ldarg.1 IL_0001: brfalse.s IL_0040 IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldstr ""Bill"" IL_0010: call ""bool string.op_Equality(string, string)"" IL_0015: brtrue.s IL_0020 IL_0017: ldarg.1 IL_0018: isinst ""Student"" IL_001d: brtrue.s IL_002b IL_001f: ret IL_0020: ldstr ""Hey Bill!"" IL_0025: call ""void System.Console.WriteLine(string)"" IL_002a: ret IL_002b: ldstr ""Hello student "" IL_0030: ldloc.0 IL_0031: ldstr ""!"" IL_0036: call ""string string.Concat(string, string, string)"" IL_003b: call ""void System.Console.WriteLine(string)"" IL_0040: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void NoRedundantPropertyRead10() { // Currently we don't combine these redundant property reads. // However we could do so in the future. var source = @"using System; public abstract class Person { public abstract string Name { get; set; } } public class Student : Person { public override string Name { get; set; } } public class C { public void M(Person p) { switch (p) { case { Name: ""Bill"" }: Console.WriteLine(""Hey Bill!""); break; case Student { Name: var name }: Console.WriteLine($""Hello student { name}!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 73 (0x49) .maxstack 3 .locals init (string V_0, //name Student V_1) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0048 IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: ldstr ""Bill"" IL_000e: call ""bool string.op_Equality(string, string)"" IL_0013: brtrue.s IL_0028 IL_0015: ldarg.1 IL_0016: isinst ""Student"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: brfalse.s IL_0048 IL_001f: ldloc.1 IL_0020: callvirt ""string Person.Name.get"" IL_0025: stloc.0 IL_0026: br.s IL_0033 IL_0028: ldstr ""Hey Bill!"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ret IL_0033: ldstr ""Hello student "" IL_0038: ldloc.0 IL_0039: ldstr ""!"" IL_003e: call ""string string.Concat(string, string, string)"" IL_0043: call ""void System.Console.WriteLine(string)"" IL_0048: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void CombiningRedundantPropertyReadsDoesNotChangeNullabilityAnalysis01() { // Currently we don't combine the redundant property reads at all. // However this could be improved in the future so this test is important var source = @"using System; #nullable enable public class Person { public virtual string? Name { get; } } public class Student : Person { public override string Name { get => base.Name ?? """"; } } public class C { public void M(Person p) { switch (p) { case { Name: ""Bill""}: Console.WriteLine(""Hey Bill!""); break; case Student { Name: var name }: Console.WriteLine($""Student has name of length { name.Length }!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 78 (0x4e) .maxstack 2 .locals init (string V_0, //name Student V_1) IL_0000: ldarg.1 IL_0001: brfalse.s IL_004d IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: ldstr ""Bill"" IL_000e: call ""bool string.op_Equality(string, string)"" IL_0013: brtrue.s IL_0028 IL_0015: ldarg.1 IL_0016: isinst ""Student"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: brfalse.s IL_004d IL_001f: ldloc.1 IL_0020: callvirt ""string Person.Name.get"" IL_0025: stloc.0 IL_0026: br.s IL_0033 IL_0028: ldstr ""Hey Bill!"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ret IL_0033: ldstr ""Student has name of length {0}!"" IL_0038: ldloc.0 IL_0039: callvirt ""int string.Length.get"" IL_003e: box ""int"" IL_0043: call ""string string.Format(string, object)"" IL_0048: call ""void System.Console.WriteLine(string)"" IL_004d: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void CombiningRedundantPropertyReadsDoesNotChangeNullabilityAnalysis02() { var source = @"using System; #nullable enable public class Person { public string? Name { get;} } public class Student : Person { } public class C { public void M(Person p) { switch (p) { case { Name: var name } when name is null: Console.WriteLine($""Hey { name }""); break; case Student { Name: var name } when name != null: Console.WriteLine($""Student has name of length { name.Length }!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 75 (0x4b) .maxstack 2 .locals init (string V_0, //name string V_1, //name Person V_2) IL_0000: ldarg.1 IL_0001: stloc.2 IL_0002: ldloc.2 IL_0003: brfalse.s IL_004a IL_0005: ldloc.2 IL_0006: callvirt ""string Person.Name.get"" IL_000b: stloc.0 IL_000c: br.s IL_0017 IL_000e: ldloc.2 IL_000f: isinst ""Student"" IL_0014: brtrue.s IL_002b IL_0016: ret IL_0017: ldloc.0 IL_0018: brtrue.s IL_000e IL_001a: ldstr ""Hey "" IL_001f: ldloc.0 IL_0020: call ""string string.Concat(string, string)"" IL_0025: call ""void System.Console.WriteLine(string)"" IL_002a: ret IL_002b: ldloc.0 IL_002c: stloc.1 IL_002d: ldloc.1 IL_002e: brfalse.s IL_004a IL_0030: ldstr ""Student has name of length {0}!"" IL_0035: ldloc.1 IL_0036: callvirt ""int string.Length.get"" IL_003b: box ""int"" IL_0040: call ""string string.Format(string, object)"" IL_0045: call ""void System.Console.WriteLine(string)"" IL_004a: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void CombiningRedundantPropertyReadsDoesNotChangeNullabilityAnalysis03() { var source = @"using System; #nullable enable public class Person { public string? Name { get; } } public class Student : Person { } public class C { public void M(Person p) { switch (p) { case { Name: string name }: Console.WriteLine($""Hey {name}""); break; case Student { Name: var name }: Console.WriteLine($""Student has name of length { name.Length }!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (19,66): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine($"Student has name of length { name.Length }!"); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "name").WithLocation(19, 66)); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 68 (0x44) .maxstack 2 .locals init (string V_0, //name string V_1) //name IL_0000: ldarg.1 IL_0001: brfalse.s IL_0043 IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brtrue.s IL_0016 IL_000d: ldarg.1 IL_000e: isinst ""Student"" IL_0013: brtrue.s IL_0027 IL_0015: ret IL_0016: ldstr ""Hey "" IL_001b: ldloc.0 IL_001c: call ""string string.Concat(string, string)"" IL_0021: call ""void System.Console.WriteLine(string)"" IL_0026: ret IL_0027: ldloc.0 IL_0028: stloc.1 IL_0029: ldstr ""Student has name of length {0}!"" IL_002e: ldloc.1 IL_002f: callvirt ""int string.Length.get"" IL_0034: box ""int"" IL_0039: call ""string string.Format(string, object)"" IL_003e: call ""void System.Console.WriteLine(string)"" IL_0043: ret }"); } [Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")] public void DoNotCombineDifferentPropertyReadsWithSameName() { var source = @"using System; public class Person { public string Name { get; set; } } public class Student : Person { public new string Name { get; set; } } public class C { public void M(Person p) { switch (p) { case { Name: ""Bill"" }: Console.WriteLine(""Hey Bill!""); break; case Student { Name: var name }: Console.WriteLine($""Hello student { name}!""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M", @"{ // Code size 73 (0x49) .maxstack 3 .locals init (string V_0, //name Student V_1) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0048 IL_0003: ldarg.1 IL_0004: callvirt ""string Person.Name.get"" IL_0009: ldstr ""Bill"" IL_000e: call ""bool string.op_Equality(string, string)"" IL_0013: brtrue.s IL_0028 IL_0015: ldarg.1 IL_0016: isinst ""Student"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: brfalse.s IL_0048 IL_001f: ldloc.1 IL_0020: callvirt ""string Student.Name.get"" IL_0025: stloc.0 IL_0026: br.s IL_0033 IL_0028: ldstr ""Hey Bill!"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ret IL_0033: ldstr ""Hello student "" IL_0038: ldloc.0 IL_0039: ldstr ""!"" IL_003e: call ""string string.Concat(string, string, string)"" IL_0043: call ""void System.Console.WriteLine(string)"" IL_0048: ret }"); } [Fact, WorkItem(51801, "https://github.com/dotnet/roslyn/issues/51801")] public void PropertyOverrideLacksAccessor() { var source = @" #nullable enable class Base { public virtual bool IsOk { get { return true; } set { } } } class C : Base { public override bool IsOk { set { } } public string? Value { get; } public string M() { switch (this) { case { IsOk: true }: return Value; default: return Value; } } } "; var verifier = CompileAndVerify(source); verifier.VerifyIL("C.M", @" { // Code size 26 (0x1a) .maxstack 1 .locals init (C V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brfalse.s IL_0013 IL_0005: ldloc.0 IL_0006: callvirt ""bool Base.IsOk.get"" IL_000b: pop IL_000c: ldarg.0 IL_000d: call ""string C.Value.get"" IL_0012: ret IL_0013: ldarg.0 IL_0014: call ""string C.Value.get"" IL_0019: ret }"); } [Fact, WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")] public void PatternsVsAs01() { var source = @"using System.Collections; using System.Collections.Generic; class Program { static void Main() { } internal static bool TryGetCount1<T>(IEnumerable<T> source, out int count) { ICollection nonGeneric = source as ICollection; if (nonGeneric != null) { count = nonGeneric.Count; return true; } ICollection<T> generic = source as ICollection<T>; if (generic != null) { count = generic.Count; return true; } count = -1; return false; } internal static bool TryGetCount2<T>(IEnumerable<T> source, out int count) { switch (source) { case ICollection nonGeneric: count = nonGeneric.Count; return true; case ICollection<T> generic: count = generic.Count; return true; default: count = -1; return false; } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("Program.TryGetCount1<T>", @"{ // Code size 45 (0x2d) .maxstack 2 .locals init (System.Collections.ICollection V_0, //nonGeneric System.Collections.Generic.ICollection<T> V_1) //generic IL_0000: ldarg.0 IL_0001: isinst ""System.Collections.ICollection"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0014 IL_000a: ldarg.1 IL_000b: ldloc.0 IL_000c: callvirt ""int System.Collections.ICollection.Count.get"" IL_0011: stind.i4 IL_0012: ldc.i4.1 IL_0013: ret IL_0014: ldarg.0 IL_0015: isinst ""System.Collections.Generic.ICollection<T>"" IL_001a: stloc.1 IL_001b: ldloc.1 IL_001c: brfalse.s IL_0028 IL_001e: ldarg.1 IL_001f: ldloc.1 IL_0020: callvirt ""int System.Collections.Generic.ICollection<T>.Count.get"" IL_0025: stind.i4 IL_0026: ldc.i4.1 IL_0027: ret IL_0028: ldarg.1 IL_0029: ldc.i4.m1 IL_002a: stind.i4 IL_002b: ldc.i4.0 IL_002c: ret }"); compVerifier.VerifyIL("Program.TryGetCount2<T>", @"{ // Code size 47 (0x2f) .maxstack 2 .locals init (System.Collections.ICollection V_0, //nonGeneric System.Collections.Generic.ICollection<T> V_1) //generic IL_0000: ldarg.0 IL_0001: isinst ""System.Collections.ICollection"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0016 IL_000a: ldarg.0 IL_000b: isinst ""System.Collections.Generic.ICollection<T>"" IL_0010: stloc.1 IL_0011: ldloc.1 IL_0012: brtrue.s IL_0020 IL_0014: br.s IL_002a IL_0016: ldarg.1 IL_0017: ldloc.0 IL_0018: callvirt ""int System.Collections.ICollection.Count.get"" IL_001d: stind.i4 IL_001e: ldc.i4.1 IL_001f: ret IL_0020: ldarg.1 IL_0021: ldloc.1 IL_0022: callvirt ""int System.Collections.Generic.ICollection<T>.Count.get"" IL_0027: stind.i4 IL_0028: ldc.i4.1 IL_0029: ret IL_002a: ldarg.1 IL_002b: ldc.i4.m1 IL_002c: stind.i4 IL_002d: ldc.i4.0 IL_002e: ret }"); } [Fact, WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")] public void PatternsVsAs02() { var source = @"using System.Collections; class Program { static void Main() { } internal static bool IsEmpty1(IEnumerable source) { var c = source as ICollection; return c != null && c.Count > 0; } internal static bool IsEmpty2(IEnumerable source) { return source is ICollection c && c.Count > 0; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("Program.IsEmpty1", @"{ // Code size 22 (0x16) .maxstack 2 .locals init (System.Collections.ICollection V_0) //c IL_0000: ldarg.0 IL_0001: isinst ""System.Collections.ICollection"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0014 IL_000a: ldloc.0 IL_000b: callvirt ""int System.Collections.ICollection.Count.get"" IL_0010: ldc.i4.0 IL_0011: cgt IL_0013: ret IL_0014: ldc.i4.0 IL_0015: ret }"); compVerifier.VerifyIL("Program.IsEmpty2", @"{ // Code size 22 (0x16) .maxstack 2 .locals init (System.Collections.ICollection V_0) //c IL_0000: ldarg.0 IL_0001: isinst ""System.Collections.ICollection"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0014 IL_000a: ldloc.0 IL_000b: callvirt ""int System.Collections.ICollection.Count.get"" IL_0010: ldc.i4.0 IL_0011: cgt IL_0013: ret IL_0014: ldc.i4.0 IL_0015: ret }"); } [Fact] [WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")] [WorkItem(1395, "https://github.com/dotnet/csharplang/issues/1395")] public void TupleSwitch01() { var source = @"using System; public class Door { public DoorState State; public enum DoorState { Opened, Closed, Locked } public enum Action { Open, Close, Lock, Unlock } public void Act0(Action action, bool haveKey = false) { Console.Write($""{State} {action}{(haveKey ? "" withKey"" : null)}""); State = ChangeState0(State, action, haveKey); Console.WriteLine($"" -> {State}""); } public void Act1(Action action, bool haveKey = false) { Console.Write($""{State} {action}{(haveKey ? "" withKey"" : null)}""); State = ChangeState1(State, action, haveKey); Console.WriteLine($"" -> {State}""); } public static DoorState ChangeState0(DoorState state, Action action, bool haveKey = false) { switch (state, action) { case (DoorState.Opened, Action.Close): return DoorState.Closed; case (DoorState.Closed, Action.Open): return DoorState.Opened; case (DoorState.Closed, Action.Lock) when haveKey: return DoorState.Locked; case (DoorState.Locked, Action.Unlock) when haveKey: return DoorState.Closed; case var (oldState, _): return oldState; } } public static DoorState ChangeState1(DoorState state, Action action, bool haveKey = false) => (state, action) switch { (DoorState.Opened, Action.Close) => DoorState.Closed, (DoorState.Closed, Action.Open) => DoorState.Opened, (DoorState.Closed, Action.Lock) when haveKey => DoorState.Locked, (DoorState.Locked, Action.Unlock) when haveKey => DoorState.Closed, _ => state }; } class Program { static void Main(string[] args) { var door = new Door(); door.Act0(Door.Action.Close); door.Act0(Door.Action.Lock); door.Act0(Door.Action.Lock, true); door.Act0(Door.Action.Open); door.Act0(Door.Action.Unlock); door.Act0(Door.Action.Unlock, true); door.Act0(Door.Action.Open); Console.WriteLine(); door = new Door(); door.Act1(Door.Action.Close); door.Act1(Door.Action.Lock); door.Act1(Door.Action.Lock, true); door.Act1(Door.Action.Open); door.Act1(Door.Action.Unlock); door.Act1(Door.Action.Unlock, true); door.Act1(Door.Action.Open); } }"; var expectedOutput = @"Opened Close -> Closed Closed Lock -> Closed Closed Lock withKey -> Locked Locked Open -> Locked Locked Unlock -> Locked Locked Unlock withKey -> Closed Closed Open -> Opened Opened Close -> Closed Closed Lock -> Closed Closed Lock withKey -> Locked Locked Open -> Locked Locked Unlock -> Locked Locked Unlock withKey -> Closed Closed Open -> Opened "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithRecursivePatterns); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("Door.ChangeState0", @"{ // Code size 61 (0x3d) .maxstack 2 .locals init (Door.DoorState V_0, //oldState Door.Action V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: switch ( IL_0018, IL_001e, IL_0027) IL_0016: br.s IL_003b IL_0018: ldloc.1 IL_0019: ldc.i4.1 IL_001a: beq.s IL_002d IL_001c: br.s IL_003b IL_001e: ldloc.1 IL_001f: brfalse.s IL_002f IL_0021: ldloc.1 IL_0022: ldc.i4.2 IL_0023: beq.s IL_0031 IL_0025: br.s IL_003b IL_0027: ldloc.1 IL_0028: ldc.i4.3 IL_0029: beq.s IL_0036 IL_002b: br.s IL_003b IL_002d: ldc.i4.1 IL_002e: ret IL_002f: ldc.i4.0 IL_0030: ret IL_0031: ldarg.2 IL_0032: brfalse.s IL_003b IL_0034: ldc.i4.2 IL_0035: ret IL_0036: ldarg.2 IL_0037: brfalse.s IL_003b IL_0039: ldc.i4.1 IL_003a: ret IL_003b: ldloc.0 IL_003c: ret }"); compVerifier.VerifyIL("Door.ChangeState1", @"{ // Code size 71 (0x47) .maxstack 2 .locals init (Door.DoorState V_0, Door.DoorState V_1, Door.Action V_2) IL_0000: ldarg.0 IL_0001: stloc.1 IL_0002: ldarg.1 IL_0003: stloc.2 IL_0004: ldloc.1 IL_0005: switch ( IL_0018, IL_001e, IL_0027) IL_0016: br.s IL_0043 IL_0018: ldloc.2 IL_0019: ldc.i4.1 IL_001a: beq.s IL_002d IL_001c: br.s IL_0043 IL_001e: ldloc.2 IL_001f: brfalse.s IL_0031 IL_0021: ldloc.2 IL_0022: ldc.i4.2 IL_0023: beq.s IL_0035 IL_0025: br.s IL_0043 IL_0027: ldloc.2 IL_0028: ldc.i4.3 IL_0029: beq.s IL_003c IL_002b: br.s IL_0043 IL_002d: ldc.i4.1 IL_002e: stloc.0 IL_002f: br.s IL_0045 IL_0031: ldc.i4.0 IL_0032: stloc.0 IL_0033: br.s IL_0045 IL_0035: ldarg.2 IL_0036: brfalse.s IL_0043 IL_0038: ldc.i4.2 IL_0039: stloc.0 IL_003a: br.s IL_0045 IL_003c: ldarg.2 IL_003d: brfalse.s IL_0043 IL_003f: ldc.i4.1 IL_0040: stloc.0 IL_0041: br.s IL_0045 IL_0043: ldarg.0 IL_0044: stloc.0 IL_0045: ldloc.0 IL_0046: ret }"); } [Fact] [WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")] [WorkItem(1395, "https://github.com/dotnet/csharplang/issues/1395")] public void SharingTemps01() { var source = @"class Program { static void Main(string[] args) { } void M1(string x) { switch (x) { case ""a"": case ""b"" when Mutate(ref x): // prevents sharing temps case ""c"": break; } } void M2(string x) { switch (x) { case ""a"": case ""b"" when Pure(x): case ""c"": break; } } static bool Mutate(ref string x) { x = null; return false; } static bool Pure(string x) { return false; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithoutRecursivePatterns); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("Program.M1", @"{ // Code size 50 (0x32) .maxstack 2 .locals init (string V_0) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldstr ""a"" IL_0008: call ""bool string.op_Equality(string, string)"" IL_000d: brtrue.s IL_0031 IL_000f: ldloc.0 IL_0010: ldstr ""b"" IL_0015: call ""bool string.op_Equality(string, string)"" IL_001a: brtrue.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""c"" IL_0022: call ""bool string.op_Equality(string, string)"" IL_0027: pop IL_0028: ret IL_0029: ldarga.s V_1 IL_002b: call ""bool Program.Mutate(ref string)"" IL_0030: pop IL_0031: ret }"); compVerifier.VerifyIL("Program.M2", @"{ // Code size 49 (0x31) .maxstack 2 .locals init (string V_0) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldstr ""a"" IL_0008: call ""bool string.op_Equality(string, string)"" IL_000d: brtrue.s IL_0030 IL_000f: ldloc.0 IL_0010: ldstr ""b"" IL_0015: call ""bool string.op_Equality(string, string)"" IL_001a: brtrue.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""c"" IL_0022: call ""bool string.op_Equality(string, string)"" IL_0027: pop IL_0028: ret IL_0029: ldarg.1 IL_002a: call ""bool Program.Pure(string)"" IL_002f: pop IL_0030: ret }"); } [Fact, WorkItem(17266, "https://github.com/dotnet/roslyn/issues/17266")] public void IrrefutablePatternInIs01() { var source = @"using System; public class C { public static void Main() { if (Get() is int index) { } Console.WriteLine(index); } public static int Get() { Console.WriteLine(""eval""); return 1; } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"eval 1"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(17266, "https://github.com/dotnet/roslyn/issues/17266")] public void IrrefutablePatternInIs02() { var source = @"using System; public class C { public static void Main() { if (Get() is Assignment(int left, var right)) { } Console.WriteLine(left); Console.WriteLine(right); } public static Assignment Get() { Console.WriteLine(""eval""); return new Assignment(1, 2); } } public struct Assignment { public int Left, Right; public Assignment(int left, int right) => (Left, Right) = (left, right); public void Deconstruct(out int left, out int right) => (left, right) = (Left, Right); } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns); compilation.VerifyDiagnostics(); var expectedOutput = @"eval 1 2"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void MissingNullCheck01() { var source = @"class Program { public static void Main() { string s = null; System.Console.WriteLine(s is string { Length: 3 }); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns); compilation.VerifyDiagnostics(); var expectedOutput = @"False"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] [WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")] [WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")] public void ConstantPatternVsUnconstrainedTypeParameter01() { var source = @"using System; class Program { static void Main() { Console.WriteLine(Test1<object>(null)); Console.WriteLine(Test1<int>(1)); Console.WriteLine(Test1<int?>(null)); Console.WriteLine(Test1<int?>(1)); Console.WriteLine(Test2<object>(0)); Console.WriteLine(Test2<int>(1)); Console.WriteLine(Test2<int?>(0)); Console.WriteLine(Test2<string>(""frog"")); Console.WriteLine(Test3<object>(""frog"")); Console.WriteLine(Test3<int>(1)); Console.WriteLine(Test3<string>(""frog"")); Console.WriteLine(Test3<int?>(1)); } public static bool Test1<T>(T t) { return t is null; } public static bool Test2<T>(T t) { return t is 0; } public static bool Test3<T>(T t) { return t is ""frog""; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"True False True False True False True False True False True False "; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("Program.Test1<T>(T)", @"{ // Code size 10 (0xa) .maxstack 2 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: ldnull IL_0007: ceq IL_0009: ret }"); compVerifier.VerifyIL("Program.Test2<T>(T)", @"{ // Code size 35 (0x23) .maxstack 2 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0021 IL_000d: ldarg.0 IL_000e: box ""T"" IL_0013: isinst ""int"" IL_0018: unbox.any ""int"" IL_001d: ldc.i4.0 IL_001e: ceq IL_0020: ret IL_0021: ldc.i4.0 IL_0022: ret } "); compVerifier.VerifyIL("Program.Test3<T>(T)", @"{ // Code size 29 (0x1d) .maxstack 2 .locals init (string V_0) IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: isinst ""string"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brfalse.s IL_001b IL_000f: ldloc.0 IL_0010: ldstr ""frog"" IL_0015: call ""bool string.op_Equality(string, string)"" IL_001a: ret IL_001b: ldc.i4.0 IL_001c: ret }"); } [Fact] [WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")] [WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")] public void ConstantPatternVsUnconstrainedTypeParameter02() { var source = @"class C<T> { internal struct S { } static bool Test(S s) { return s is 1; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C<T>.Test(C<T>.S)", @"{ // Code size 35 (0x23) .maxstack 2 IL_0000: ldarg.0 IL_0001: box ""C<T>.S"" IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0021 IL_000d: ldarg.0 IL_000e: box ""C<T>.S"" IL_0013: isinst ""int"" IL_0018: unbox.any ""int"" IL_001d: ldc.i4.1 IL_001e: ceq IL_0020: ret IL_0021: ldc.i4.0 IL_0022: ret } "); } [Fact] [WorkItem(26274, "https://github.com/dotnet/roslyn/issues/26274")] public void VariablesInSwitchExpressionArms() { var source = @"class C { public override bool Equals(object obj) => obj switch { C x1 when x1 is var x2 => x2 is var x3 && x3 is {}, _ => false }; public override int GetHashCode() => 1; public static void Main() { C c = new C(); System.Console.Write(c.Equals(new C())); System.Console.Write(c.Equals(new object())); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "TrueFalse"); compVerifier.VerifyIL("C.Equals(object)", @"{ // Code size 25 (0x19) .maxstack 2 .locals init (C V_0, //x1 C V_1, //x2 C V_2, //x3 bool V_3) IL_0000: ldarg.1 IL_0001: isinst ""C"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0015 IL_000a: ldloc.0 IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: stloc.2 IL_000e: ldloc.2 IL_000f: ldnull IL_0010: cgt.un IL_0012: stloc.3 IL_0013: br.s IL_0017 IL_0015: ldc.i4.0 IL_0016: stloc.3 IL_0017: ldloc.3 IL_0018: ret }"); } [Fact, WorkItem(26387, "https://github.com/dotnet/roslyn/issues/26387")] public void ValueTypeArgument01() { var source = @"using System; class TestHelper { static void Main() { Console.WriteLine(IsValueTypeT0(new S())); Console.WriteLine(IsValueTypeT1(new S())); Console.WriteLine(IsValueTypeT2(new S())); } static bool IsValueTypeT0<T>(T result) { return result is T; } static bool IsValueTypeT1<T>(T result) { return result is T v; } static bool IsValueTypeT2<T>(T result) { return result is T _; } } struct S { } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"True True True"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("TestHelper.IsValueTypeT0<T>(T)", @"{ // Code size 15 (0xf) .maxstack 2 .locals init (bool V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: ldnull IL_0008: cgt.un IL_000a: stloc.0 IL_000b: br.s IL_000d IL_000d: ldloc.0 IL_000e: ret }"); compVerifier.VerifyIL("TestHelper.IsValueTypeT1<T>(T)", @"{ // Code size 20 (0x14) .maxstack 1 .locals init (T V_0, //v bool V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: brfalse.s IL_000e IL_0009: ldarg.0 IL_000a: stloc.0 IL_000b: ldc.i4.1 IL_000c: br.s IL_000f IL_000e: ldc.i4.0 IL_000f: stloc.1 IL_0010: br.s IL_0012 IL_0012: ldloc.1 IL_0013: ret }"); compVerifier.VerifyIL("TestHelper.IsValueTypeT2<T>(T)", @"{ // Code size 15 (0xf) .maxstack 2 .locals init (bool V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: ldnull IL_0008: cgt.un IL_000a: stloc.0 IL_000b: br.s IL_000d IL_000d: ldloc.0 IL_000e: ret }"); } [Fact, WorkItem(26387, "https://github.com/dotnet/roslyn/issues/26387")] public void ValueTypeArgument02() { var source = @"namespace ConsoleApp1 { public class TestHelper { public static void Main() { IsValueTypeT(new Result<(Cls, IInt)>((new Cls(), new Int()))); System.Console.WriteLine(""done""); } public static void IsValueTypeT<T>(Result<T> result) { if (!(result.Value is T v)) throw new NotPossibleException(); } } public class Result<T> { public T Value { get; } public Result(T value) { Value = value; } } public class Cls { } public interface IInt { } public class Int : IInt { } public class NotPossibleException : System.Exception { } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"done"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("ConsoleApp1.TestHelper.IsValueTypeT<T>(ConsoleApp1.Result<T>)", @"{ // Code size 31 (0x1f) .maxstack 2 .locals init (T V_0, //v bool V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: callvirt ""T ConsoleApp1.Result<T>.Value.get"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: box ""T"" IL_000e: ldnull IL_000f: cgt.un IL_0011: ldc.i4.0 IL_0012: ceq IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001e IL_0018: newobj ""ConsoleApp1.NotPossibleException..ctor()"" IL_001d: throw IL_001e: ret }"); } [Fact] public void DeconstructNullableTuple_01() { var source = @" class C { static int i = 3; static (int,int)? GetNullableTuple() => (i++, i++); static void Main() { if (GetNullableTuple() is (int x1, int y1) tupl1) { System.Console.WriteLine($""x = {x1}, y = {y1}""); } if (GetNullableTuple() is (int x2, int y2) _) { System.Console.WriteLine($""x = {x2}, y = {y2}""); } switch (GetNullableTuple()) { case (int x3, int y3) s: System.Console.WriteLine($""x = {x3}, y = {y3}""); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"x = 3, y = 4 x = 5, y = 6 x = 7, y = 8"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void DeconstructNullable_01() { var source = @" class C { static int i = 3; static S? GetNullableTuple() => new S(i++, i++); static void Main() { if (GetNullableTuple() is (int x1, int y1) tupl1) { System.Console.WriteLine($""x = {x1}, y = {y1}""); } if (GetNullableTuple() is (int x2, int y2) _) { System.Console.WriteLine($""x = {x2}, y = {y2}""); } switch (GetNullableTuple()) { case (int x3, int y3) s: System.Console.WriteLine($""x = {x3}, y = {y3}""); break; } } } struct S { int x, y; public S(int X, int Y) => (this.x, this.y) = (X, Y); public void Deconstruct(out int X, out int Y) => (X, Y) = (x, y); } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"x = 3, y = 4 x = 5, y = 6 x = 7, y = 8"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(28632, "https://github.com/dotnet/roslyn/issues/28632")] public void UnboxNullableInRecursivePattern01() { var source = @" static class Program { public static int M1(int? x) { return x is int y ? y : 1; } public static int M2(int? x) { return x is { } y ? y : 2; } public static void Main() { System.Console.WriteLine(M1(null)); System.Console.WriteLine(M2(null)); System.Console.WriteLine(M1(3)); System.Console.WriteLine(M2(4)); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"1 2 3 4"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("Program.M1", @"{ // Code size 23 (0x17) .maxstack 1 .locals init (int V_0) //y IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brfalse.s IL_0013 IL_0009: ldarga.s V_0 IL_000b: call ""int int?.GetValueOrDefault()"" IL_0010: stloc.0 IL_0011: br.s IL_0015 IL_0013: ldc.i4.1 IL_0014: ret IL_0015: ldloc.0 IL_0016: ret }"); compVerifier.VerifyIL("Program.M2", @"{ // Code size 23 (0x17) .maxstack 1 .locals init (int V_0) //y IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brfalse.s IL_0013 IL_0009: ldarga.s V_0 IL_000b: call ""int int?.GetValueOrDefault()"" IL_0010: stloc.0 IL_0011: br.s IL_0015 IL_0013: ldc.i4.2 IL_0014: ret IL_0015: ldloc.0 IL_0016: ret }"); } [Fact] public void DoNotShareInputForMutatingWhenClause() { var source = @"using System; class Program { static void Main() { Console.Write(M1(1)); Console.Write(M2(1)); Console.Write(M3(1)); Console.Write(M4(1)); Console.Write(M5(1)); Console.Write(M6(1)); Console.Write(M7(1)); Console.Write(M8(1)); Console.Write(M9(1)); } public static int M1(int x) { return x switch { _ when (++x) == 5 => 1, 1 => 2, _ => 3 }; } public static int M2(int x) { return x switch { _ when (x+=1) == 5 => 1, 1 => 2, _ => 3 }; } public static int M3(int x) { return x switch { _ when ((x, _) = (5, 6)) == (0, 0) => 1, 1 => 2, _ => 3 }; } public static int M4(int x) { dynamic d = new Program(); return x switch { _ when d.M(ref x) => 1, 1 => 2, _ => 3 }; } bool M(ref int x) { x = 100; return false; } public static int M5(int x) { return x switch { _ when new Program(ref x).P => 1, 1 => 2, _ => 3 }; } public static int M6(int x) { dynamic d = x; return x switch { _ when new Program(d, ref x).P => 1, 1 => 2, _ => 3 }; } public static int M7(int x) { return x switch { _ when new Program(ref x).P && new Program().P => 1, 1 => 2, _ => 3 }; } public static int M8(int x) { dynamic d = x; return x switch { _ when new Program(d, ref x).P && new Program().P => 1, 1 => 2, _ => 3 }; } public static int M9(int x) { return x switch { _ when (x=100) == 1 => 1, 1 => 2, _ => 3 }; } Program() { } Program(ref int x) { x = 100; } Program(int a, ref int x) { x = 100; } bool P => false; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, references: new[] { CSharpRef }); compilation.VerifyDiagnostics(); var expectedOutput = @"222222222"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void GenerateStringHashOnlyOnce() { var source = @"using System; class Program { static void Main() { Console.Write(M1(string.Empty)); Console.Write(M2(string.Empty)); } public static int M1(string s) { return s switch { ""a""=>1, ""b""=>2, ""c""=>3, ""d""=>4, ""e""=>5, ""f""=>6, ""g""=>7, ""h""=>8, _ => 9 }; } public static int M2(string s) { return s switch { ""a""=>1, ""b""=>2, ""c""=>3, ""d""=>4, ""e""=>5, ""f""=>6, ""g""=>7, ""h""=>8, _ => 9 }; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"99"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void BindVariablesInWhenClause() { var source = @"using System; class Program { static void Main() { var t = (1, 2); switch (t) { case var (x, y) when x+1 == y: Console.Write(1); break; } Console.Write(t switch { var (x, y) when x+1 == y => 1, _ => 2 }); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"11"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void MissingExceptions_01() { var source = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } static class C { public static bool M(int i) => i switch { 1 => true }; } "; var compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseDll); compilation.GetDiagnostics().Verify( // (9,38): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '0' is not covered. // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("0").WithLocation(9, 38) ); compilation.GetEmitDiagnostics().Verify( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (9,5): error CS0518: Predefined type 'System.Byte' is not defined or imported // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "public static bool M(int i) => i switch { 1 => true };").WithArguments("System.Byte").WithLocation(9, 5), // (9,5): error CS0518: Predefined type 'System.Byte' is not defined or imported // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "public static bool M(int i) => i switch { 1 => true };").WithArguments("System.Byte").WithLocation(9, 5), // (9,5): error CS0518: Predefined type 'System.Int16' is not defined or imported // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "public static bool M(int i) => i switch { 1 => true };").WithArguments("System.Int16").WithLocation(9, 5), // (9,5): error CS0518: Predefined type 'System.Int16' is not defined or imported // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "public static bool M(int i) => i switch { 1 => true };").WithArguments("System.Int16").WithLocation(9, 5), // (9,5): error CS0518: Predefined type 'System.Int64' is not defined or imported // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "public static bool M(int i) => i switch { 1 => true };").WithArguments("System.Int64").WithLocation(9, 5), // (9,5): error CS0518: Predefined type 'System.Int64' is not defined or imported // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "public static bool M(int i) => i switch { 1 => true };").WithArguments("System.Int64").WithLocation(9, 5), // (9,36): error CS0656: Missing compiler required member 'System.InvalidOperationException..ctor' // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "i switch { 1 => true }").WithArguments("System.InvalidOperationException", ".ctor").WithLocation(9, 36), // (9,38): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '0' is not covered. // public static bool M(int i) => i switch { 1 => true }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("0").WithLocation(9, 38) ); } [Fact, WorkItem(32774, "https://github.com/dotnet/roslyn/issues/32774")] public void BadCode_32774() { var source = @" public class Class1 { static void Main() { System.Console.WriteLine(SwitchCaseThatFails(12.123)); } public static bool SwitchCaseThatFails(object someObject) { switch (someObject) { case IObject x when x.SubObject != null: return false; case IOtherObject x: return false; case double x: return true; default: return false; } } public interface IObject { IObject SubObject { get; } } public interface IOtherObject { } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"True"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("Class1.SwitchCaseThatFails", @"{ // Code size 97 (0x61) .maxstack 1 .locals init (Class1.IObject V_0, //x Class1.IOtherObject V_1, //x double V_2, //x object V_3, object V_4, bool V_5) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.s V_4 IL_0004: ldloc.s V_4 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: isinst ""Class1.IObject"" IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: brtrue.s IL_003c IL_0011: br.s IL_001f IL_0013: ldloc.3 IL_0014: isinst ""Class1.IOtherObject"" IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: brtrue.s IL_004b IL_001d: br.s IL_0059 IL_001f: ldloc.3 IL_0020: isinst ""Class1.IOtherObject"" IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: brtrue.s IL_004b IL_0029: br.s IL_002b IL_002b: ldloc.3 IL_002c: isinst ""double"" IL_0031: brfalse.s IL_0059 IL_0033: ldloc.3 IL_0034: unbox.any ""double"" IL_0039: stloc.2 IL_003a: br.s IL_0052 IL_003c: ldloc.0 IL_003d: callvirt ""Class1.IObject Class1.IObject.SubObject.get"" IL_0042: brtrue.s IL_0046 IL_0044: br.s IL_0013 IL_0046: ldc.i4.0 IL_0047: stloc.s V_5 IL_0049: br.s IL_005e IL_004b: br.s IL_004d IL_004d: ldc.i4.0 IL_004e: stloc.s V_5 IL_0050: br.s IL_005e IL_0052: br.s IL_0054 IL_0054: ldc.i4.1 IL_0055: stloc.s V_5 IL_0057: br.s IL_005e IL_0059: ldc.i4.0 IL_005a: stloc.s V_5 IL_005c: br.s IL_005e IL_005e: ldloc.s V_5 IL_0060: ret }"); } // Possible test helper bug on Linux; see https://github.com/dotnet/roslyn/issues/33356 [ConditionalFact(typeof(WindowsOnly))] public void SwitchExpressionSequencePoints() { string source = @" public class Program { public static void Main() { int i = 0; var y = (i switch { 0 => new Program(), 1 => new Program(), _ => new Program(), }).Chain(); y.Chain2(); } public Program Chain() => this; public Program Chain2() => this; } "; var v = CompileAndVerify(source, options: TestOptions.DebugExe); v.VerifyIL(qualifiedMethodName: "Program.Main", @" { // Code size 61 (0x3d) .maxstack 2 .locals init (int V_0, //i Program V_1, //y Program V_2) // sequence point: { IL_0000: nop // sequence point: int i = 0; IL_0001: ldc.i4.0 IL_0002: stloc.0 // sequence point: var y = (i s ... }).Chain() IL_0003: ldc.i4.1 IL_0004: brtrue.s IL_0007 // sequence point: switch ... } IL_0006: nop // sequence point: <hidden> IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_001a IL_0010: br.s IL_0022 // sequence point: new Program() IL_0012: newobj ""Program..ctor()"" IL_0017: stloc.2 IL_0018: br.s IL_002a // sequence point: new Program() IL_001a: newobj ""Program..ctor()"" IL_001f: stloc.2 IL_0020: br.s IL_002a // sequence point: new Program() IL_0022: newobj ""Program..ctor()"" IL_0027: stloc.2 IL_0028: br.s IL_002a // sequence point: <hidden> IL_002a: ldc.i4.1 IL_002b: brtrue.s IL_002e // sequence point: var y = (i s ... }).Chain() IL_002d: nop // sequence point: <hidden> IL_002e: ldloc.2 IL_002f: callvirt ""Program Program.Chain()"" IL_0034: stloc.1 // sequence point: y.Chain2(); IL_0035: ldloc.1 IL_0036: callvirt ""Program Program.Chain2()"" IL_003b: pop // sequence point: } IL_003c: ret } ", sequencePoints: "Program.Main", source: source); } [Fact, WorkItem(33675, "https://github.com/dotnet/roslyn/issues/33675")] public void ParsingParenthesizedExpressionAsPatternOfExpressionSwitch() { var source = @" public class Class1 { static void Main() { System.Console.Write(M(42)); System.Console.Write(M(41)); } static bool M(object o) { const int X = 42; return o switch { (X) => true, _ => false }; } }"; foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe }) { var compilation = CreateCompilation(source, options: options); compilation.VerifyDiagnostics(); var expectedOutput = @"TrueFalse"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); if (options.OptimizationLevel == OptimizationLevel.Debug) { compVerifier.VerifyIL("Class1.M", @" { // Code size 45 (0x2d) .maxstack 2 .locals init (bool V_0, int V_1, bool V_2) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: isinst ""int"" IL_000b: brfalse.s IL_001f IL_000d: ldarg.0 IL_000e: unbox.any ""int"" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: ldc.i4.s 42 IL_0017: beq.s IL_001b IL_0019: br.s IL_001f IL_001b: ldc.i4.1 IL_001c: stloc.0 IL_001d: br.s IL_0023 IL_001f: ldc.i4.0 IL_0020: stloc.0 IL_0021: br.s IL_0023 IL_0023: ldc.i4.1 IL_0024: brtrue.s IL_0027 IL_0026: nop IL_0027: ldloc.0 IL_0028: stloc.2 IL_0029: br.s IL_002b IL_002b: ldloc.2 IL_002c: ret } "); } else { compVerifier.VerifyIL("Class1.M", @"{ // Code size 26 (0x1a) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: isinst ""int"" IL_0006: brfalse.s IL_0016 IL_0008: ldarg.0 IL_0009: unbox.any ""int"" IL_000e: ldc.i4.s 42 IL_0010: bne.un.s IL_0016 IL_0012: ldc.i4.1 IL_0013: stloc.0 IL_0014: br.s IL_0018 IL_0016: ldc.i4.0 IL_0017: stloc.0 IL_0018: ldloc.0 IL_0019: ret }"); } } } [Fact, WorkItem(35584, "https://github.com/dotnet/roslyn/issues/35584")] public void MatchToTypeParameterUnbox_01() { var source = @" class Program { public static void Main() => System.Console.WriteLine(P<int>(0)); public static string P<T>(T t) => (t is object o) ? o.ToString() : string.Empty; } "; var expectedOutput = @"0"; foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe }) { var compilation = CreateCompilation(source, options: options); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); if (options.OptimizationLevel == OptimizationLevel.Debug) { compVerifier.VerifyIL("Program.P<T>", @"{ // Code size 24 (0x18) .maxstack 1 .locals init (object V_0) //o IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0011 IL_000a: ldsfld ""string string.Empty"" IL_000f: br.s IL_0017 IL_0011: ldloc.0 IL_0012: callvirt ""string object.ToString()"" IL_0017: ret } "); } else { compVerifier.VerifyIL("Program.P<T>", @"{ // Code size 23 (0x17) .maxstack 1 .locals init (object V_0) //o IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0010 IL_000a: ldsfld ""string string.Empty"" IL_000f: ret IL_0010: ldloc.0 IL_0011: callvirt ""string object.ToString()"" IL_0016: ret } "); } } } [Fact, WorkItem(35584, "https://github.com/dotnet/roslyn/issues/35584")] public void MatchToTypeParameterUnbox_02() { var source = @"using System; class Program { public static void Main() { var generic = new Generic<int>(0); } } public class Generic<T> { public Generic(T value) { if (value is object obj && obj == null) { throw new Exception(""Kaboom!""); } } } "; var expectedOutput = @""; foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe }) { var compilation = CreateCompilation(source, options: options); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); if (options.OptimizationLevel == OptimizationLevel.Debug) { compVerifier.VerifyIL("Generic<T>..ctor(T)", @"{ // Code size 42 (0x2a) .maxstack 2 .locals init (object V_0, //obj bool V_1) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: nop IL_0008: ldarg.1 IL_0009: box ""T"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: brfalse.s IL_0018 IL_0012: ldloc.0 IL_0013: ldnull IL_0014: ceq IL_0016: br.s IL_0019 IL_0018: ldc.i4.0 IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: brfalse.s IL_0029 IL_001d: nop IL_001e: ldstr ""Kaboom!"" IL_0023: newobj ""System.Exception..ctor(string)"" IL_0028: throw IL_0029: ret } "); } else { compVerifier.VerifyIL("Generic<T>..ctor(T)", @"{ // Code size 31 (0x1f) .maxstack 1 .locals init (object V_0) //obj IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.1 IL_0007: box ""T"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: brfalse.s IL_001e IL_0010: ldloc.0 IL_0011: brtrue.s IL_001e IL_0013: ldstr ""Kaboom!"" IL_0018: newobj ""System.Exception..ctor(string)"" IL_001d: throw IL_001e: ret } "); } } } [Fact, WorkItem(35584, "https://github.com/dotnet/roslyn/issues/35584")] public void MatchToTypeParameterUnbox_03() { var source = @"using System; class Program { public static void Main() => System.Console.WriteLine(P<Enum>(null)); public static string P<T>(T t) where T: Enum => (t is ValueType o) ? o.ToString() : ""1""; } "; var expectedOutput = @"1"; foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe }) { var compilation = CreateCompilation(source, options: options); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); if (options.OptimizationLevel == OptimizationLevel.Debug) { compVerifier.VerifyIL("Program.P<T>", @"{ // Code size 24 (0x18) .maxstack 1 .locals init (System.ValueType V_0) //o IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0011 IL_000a: ldstr ""1"" IL_000f: br.s IL_0017 IL_0011: ldloc.0 IL_0012: callvirt ""string object.ToString()"" IL_0017: ret } "); } else { compVerifier.VerifyIL("Program.P<T>", @"{ // Code size 23 (0x17) .maxstack 1 .locals init (System.ValueType V_0) //o IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0010 IL_000a: ldstr ""1"" IL_000f: ret IL_0010: ldloc.0 IL_0011: callvirt ""string object.ToString()"" IL_0016: ret } "); } } } [Fact] public void CompileTimeRuntimeInstanceofMismatch_01() { var source = @"using System; class Program { static void Main() { M(new byte[1]); M(new sbyte[1]); M(new Ebyte[1]); M(new Esbyte[1]); M(new short[1]); M(new ushort[1]); M(new Eshort[1]); M(new Eushort[1]); M(new int[1]); M(new uint[1]); M(new Eint[1]); M(new Euint[1]); M(new int[1][]); M(new uint[1][]); M(new Eint[1][]); M(new Euint[1][]); M(new long[1]); M(new ulong[1]); M(new Elong[1]); M(new Eulong[1]); M(new IntPtr[1]); M(new UIntPtr[1]); M(new IntPtr[1][]); M(new UIntPtr[1][]); } static void M(object o) { switch (o) { case byte[] _ when o.GetType() == typeof(byte[]): Console.WriteLine(""byte[]""); break; case sbyte[] _ when o.GetType() == typeof(sbyte[]): Console.WriteLine(""sbyte[]""); break; case Ebyte[] _ when o.GetType() == typeof(Ebyte[]): Console.WriteLine(""Ebyte[]""); break; case Esbyte[] _ when o.GetType() == typeof(Esbyte[]): Console.WriteLine(""Esbyte[]""); break; case short[] _ when o.GetType() == typeof(short[]): Console.WriteLine(""short[]""); break; case ushort[] _ when o.GetType() == typeof(ushort[]): Console.WriteLine(""ushort[]""); break; case Eshort[] _ when o.GetType() == typeof(Eshort[]): Console.WriteLine(""Eshort[]""); break; case Eushort[] _ when o.GetType() == typeof(Eushort[]): Console.WriteLine(""Eushort[]""); break; case int[] _ when o.GetType() == typeof(int[]): Console.WriteLine(""int[]""); break; case uint[] _ when o.GetType() == typeof(uint[]): Console.WriteLine(""uint[]""); break; case Eint[] _ when o.GetType() == typeof(Eint[]): Console.WriteLine(""Eint[]""); break; case Euint[] _ when o.GetType() == typeof(Euint[]): Console.WriteLine(""Euint[]""); break; case int[][] _ when o.GetType() == typeof(int[][]): Console.WriteLine(""int[][]""); break; case uint[][] _ when o.GetType() == typeof(uint[][]): Console.WriteLine(""uint[][]""); break; case Eint[][] _ when o.GetType() == typeof(Eint[][]): Console.WriteLine(""Eint[][]""); break; case Euint[][] _ when o.GetType() == typeof(Euint[][]): Console.WriteLine(""Euint[][]""); break; case long[] _ when o.GetType() == typeof(long[]): Console.WriteLine(""long[]""); break; case ulong[] _ when o.GetType() == typeof(ulong[]): Console.WriteLine(""ulong[]""); break; case Elong[] _ when o.GetType() == typeof(Elong[]): Console.WriteLine(""Elong[]""); break; case Eulong[] _ when o.GetType() == typeof(Eulong[]): Console.WriteLine(""Eulong[]""); break; case IntPtr[] _ when o.GetType() == typeof(IntPtr[]): Console.WriteLine(""IntPtr[]""); break; case UIntPtr[] _ when o.GetType() == typeof(UIntPtr[]): Console.WriteLine(""UIntPtr[]""); break; case IntPtr[][] _ when o.GetType() == typeof(IntPtr[][]): Console.WriteLine(""IntPtr[][]""); break; case UIntPtr[][] _ when o.GetType() == typeof(UIntPtr[][]): Console.WriteLine(""UIntPtr[][]""); break; default: Console.WriteLine(""oops: "" + o.GetType()); break; } } } enum Ebyte : byte {} enum Esbyte : sbyte {} enum Eshort : short {} enum Eushort : ushort {} enum Eint : int {} enum Euint : uint {} enum Elong : long {} enum Eulong : ulong {} "; var expectedOutput = @"byte[] sbyte[] Ebyte[] Esbyte[] short[] ushort[] Eshort[] Eushort[] int[] uint[] Eint[] Euint[] int[][] uint[][] Eint[][] Euint[][] long[] ulong[] Elong[] Eulong[] IntPtr[] UIntPtr[] IntPtr[][] UIntPtr[][] "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: expectedOutput); compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void CompileTimeRuntimeInstanceofMismatch_02() { var source = @"using System; class Program { static void Main() { M(new byte[1]); M(new sbyte[1]); } static void M(object o) { switch (o) { case byte[] _: Console.WriteLine(""byte[]""); break; case sbyte[] _: // not subsumed, even though it will never occur due to CLR behavior Console.WriteLine(""sbyte[]""); break; } } } "; var expectedOutput = @"byte[] byte[] "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: expectedOutput); compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] [WorkItem(36496, "https://github.com/dotnet/roslyn/issues/36496")] public void EmptyVarPatternVsDeconstruct() { var source = @"using System; public class C { public static void Main() { Console.Write(M(new C())); Console.Write(M(null)); } public static bool M(C c) { return c is var (); } public void Deconstruct() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "TrueFalse"); compVerifier.VerifyIL("C.M(C)", @" { // Code size 5 (0x5) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldnull IL_0002: cgt.un IL_0004: ret } "); } [Fact] [WorkItem(36496, "https://github.com/dotnet/roslyn/issues/36496")] public void EmptyPositionalPatternVsDeconstruct() { var source = @"using System; public class C { public static void Main() { Console.Write(M(new C())); Console.Write(M(null)); } public static bool M(C c) { return c is (); } public void Deconstruct() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "TrueFalse"); compVerifier.VerifyIL("C.M(C)", @" { // Code size 5 (0x5) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldnull IL_0002: cgt.un IL_0004: ret } "); } [Fact, WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")] public void NoRedundantNullCheckForStringConstantPattern_01() { var source = @"public class C { public static bool M1(string s) => s is ""Frog""; public static bool M2(string s) => s == ""Frog""; public static bool M3(string s) => s switch { ""Frog"" => true, _ => false }; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1(string)", @" { // Code size 12 (0xc) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldstr ""Frog"" IL_0006: call ""bool string.op_Equality(string, string)"" IL_000b: ret } "); compVerifier.VerifyIL("C.M2(string)", @" { // Code size 12 (0xc) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldstr ""Frog"" IL_0006: call ""bool string.op_Equality(string, string)"" IL_000b: ret } "); compVerifier.VerifyIL("C.M3(string)", @" { // Code size 21 (0x15) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: ldstr ""Frog"" IL_0006: call ""bool string.op_Equality(string, string)"" IL_000b: brfalse.s IL_0011 IL_000d: ldc.i4.1 IL_000e: stloc.0 IL_000f: br.s IL_0013 IL_0011: ldc.i4.0 IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ret } "); } [Fact, WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")] public void NoRedundantNullCheckForStringConstantPattern_02() { var source = @"public class C { public static bool M1(string s) => s switch { ""Frog"" => true, ""Newt"" => true, _ => false }; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1(string)", @" { // Code size 40 (0x28) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: ldstr ""Frog"" IL_0006: call ""bool string.op_Equality(string, string)"" IL_000b: brtrue.s IL_001c IL_000d: ldarg.0 IL_000e: ldstr ""Newt"" IL_0013: call ""bool string.op_Equality(string, string)"" IL_0018: brtrue.s IL_0020 IL_001a: br.s IL_0024 IL_001c: ldc.i4.1 IL_001d: stloc.0 IL_001e: br.s IL_0026 IL_0020: ldc.i4.1 IL_0021: stloc.0 IL_0022: br.s IL_0026 IL_0024: ldc.i4.0 IL_0025: stloc.0 IL_0026: ldloc.0 IL_0027: ret } "); } [Fact, WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")] public void NoRedundantNullCheckForStringConstantPattern_03() { var source = @"public class C { public static bool M1(System.Type x) => x is { Name: ""Program"" }; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1(System.Type)", @" { // Code size 22 (0x16) .maxstack 2 IL_0000: ldarg.0 IL_0001: brfalse.s IL_0014 IL_0003: ldarg.0 IL_0004: callvirt ""string System.Reflection.MemberInfo.Name.get"" IL_0009: ldstr ""Program"" IL_000e: call ""bool string.op_Equality(string, string)"" IL_0013: ret IL_0014: ldc.i4.0 IL_0015: ret } "); } [Fact] [WorkItem(42912, "https://github.com/dotnet/roslyn/issues/42912")] [WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")] public void NoRedundantNullCheckForNullableConstantPattern_04() { // Note that we do not produce the same code for `x is 1` and `x == 1`. // The latter has been optimized to avoid branches. var source = @"public class C { public static bool M1(int? x) => x is 1; public static bool M2(int? x) => x == 1; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation); compVerifier.VerifyIL("C.M1(int?)", @" { // Code size 22 (0x16) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brfalse.s IL_0014 IL_0009: ldarga.s V_0 IL_000b: call ""int int?.GetValueOrDefault()"" IL_0010: ldc.i4.1 IL_0011: ceq IL_0013: ret IL_0014: ldc.i4.0 IL_0015: ret } "); compVerifier.VerifyIL("C.M2(int?)", @" { // Code size 23 (0x17) .maxstack 2 .locals init (int? V_0, int V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldc.i4.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""int int?.GetValueOrDefault()"" IL_000b: ldloc.1 IL_000c: ceq IL_000e: ldloca.s V_0 IL_0010: call ""bool int?.HasValue.get"" IL_0015: and IL_0016: ret } "); } [Fact] public void SwitchExpressionAsExceptionFilter_01() { var source = @" using System; class C { const string K1 = ""frog""; const string K2 = ""toad""; public static void M(string msg) { try { T(msg); } catch (Exception e) when (e.Message switch { K1 => true, K2 => true, _ => false, }) { throw new Exception(e.Message); } catch { } } static void T(string msg) { throw new Exception(msg); } static void Main() { Try(K1); Try(K2); Try(""fox""); } static void Try(string s) { try { M(s); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } "; var expectedOutput = @"frog toad"; foreach (var compilationOptions in new[] { TestOptions.ReleaseExe, TestOptions.DebugExe }) { var compilation = CreateCompilation(source, options: compilationOptions); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); if (compilationOptions.OptimizationLevel == OptimizationLevel.Debug) { compVerifier.VerifyIL("C.M(string)", @" { // Code size 108 (0x6c) .maxstack 2 .locals init (System.Exception V_0, //e bool V_1, string V_2, bool V_3) IL_0000: nop .try { IL_0001: nop IL_0002: ldarg.0 IL_0003: call ""void C.T(string)"" IL_0008: nop IL_0009: nop IL_000a: leave.s IL_006b } filter { IL_000c: isinst ""System.Exception"" IL_0011: dup IL_0012: brtrue.s IL_0018 IL_0014: pop IL_0015: ldc.i4.0 IL_0016: br.s IL_0056 IL_0018: stloc.0 IL_0019: ldloc.0 IL_001a: callvirt ""string System.Exception.Message.get"" IL_001f: stloc.2 IL_0020: ldc.i4.1 IL_0021: brtrue.s IL_0024 IL_0023: nop IL_0024: ldloc.2 IL_0025: ldstr ""frog"" IL_002a: call ""bool string.op_Equality(string, string)"" IL_002f: brtrue.s IL_0040 IL_0031: ldloc.2 IL_0032: ldstr ""toad"" IL_0037: call ""bool string.op_Equality(string, string)"" IL_003c: brtrue.s IL_0044 IL_003e: br.s IL_0048 IL_0040: ldc.i4.1 IL_0041: stloc.1 IL_0042: br.s IL_004c IL_0044: ldc.i4.1 IL_0045: stloc.1 IL_0046: br.s IL_004c IL_0048: ldc.i4.0 IL_0049: stloc.1 IL_004a: br.s IL_004c IL_004c: ldc.i4.1 IL_004d: brtrue.s IL_0050 IL_004f: nop IL_0050: ldloc.1 IL_0051: stloc.3 IL_0052: ldloc.3 IL_0053: ldc.i4.0 IL_0054: cgt.un IL_0056: endfilter } // end filter { // handler IL_0058: pop IL_0059: nop IL_005a: ldloc.0 IL_005b: callvirt ""string System.Exception.Message.get"" IL_0060: newobj ""System.Exception..ctor(string)"" IL_0065: throw } catch object { IL_0066: pop IL_0067: nop IL_0068: nop IL_0069: leave.s IL_006b } IL_006b: ret } "); } else { compVerifier.VerifyIL("C.M(string)", @" { // Code size 89 (0x59) .maxstack 2 .locals init (System.Exception V_0, //e bool V_1, string V_2) .try { IL_0000: ldarg.0 IL_0001: call ""void C.T(string)"" IL_0006: leave.s IL_0058 } filter { IL_0008: isinst ""System.Exception"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_0046 IL_0014: stloc.0 IL_0015: ldloc.0 IL_0016: callvirt ""string System.Exception.Message.get"" IL_001b: stloc.2 IL_001c: ldloc.2 IL_001d: ldstr ""frog"" IL_0022: call ""bool string.op_Equality(string, string)"" IL_0027: brtrue.s IL_0038 IL_0029: ldloc.2 IL_002a: ldstr ""toad"" IL_002f: call ""bool string.op_Equality(string, string)"" IL_0034: brtrue.s IL_003c IL_0036: br.s IL_0040 IL_0038: ldc.i4.1 IL_0039: stloc.1 IL_003a: br.s IL_0042 IL_003c: ldc.i4.1 IL_003d: stloc.1 IL_003e: br.s IL_0042 IL_0040: ldc.i4.0 IL_0041: stloc.1 IL_0042: ldloc.1 IL_0043: ldc.i4.0 IL_0044: cgt.un IL_0046: endfilter } // end filter { // handler IL_0048: pop IL_0049: ldloc.0 IL_004a: callvirt ""string System.Exception.Message.get"" IL_004f: newobj ""System.Exception..ctor(string)"" IL_0054: throw } catch object { IL_0055: pop IL_0056: leave.s IL_0058 } IL_0058: ret } "); } } } [Fact] public void SwitchExpressionAsExceptionFilter_02() { var source = @" using System; class C { public static void Main() { try { throw new Exception(); } catch when ((3 is int i) switch { true when M(() => i) => true, _ => false }) { Console.WriteLine(""correct""); } } static bool M(Func<int> func) { func(); return true; } } "; var expectedOutput = @"correct"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] [WorkItem(48259, "https://github.com/dotnet/roslyn/issues/48259")] public void SwitchExpressionAsExceptionFilter_03() { var source = @" using System; using System.Threading.Tasks; public static class Program { static async Task Main() { Exception ex = new ArgumentException(); try { throw ex; } catch (Exception e) when (e switch { InvalidOperationException => true, _ => false }) { return; } catch (Exception) { Console.WriteLine(""correct""); } } } "; var expectedOutput = "correct"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (7,23): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // static async Task Main() Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(7, 23)); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] [WorkItem(48259, "https://github.com/dotnet/roslyn/issues/48259")] public void SwitchExpressionAsExceptionFilter_04() { var source = @" using System; using System.Threading.Tasks; public static class Program { static async Task Main() { Exception ex = new ArgumentException(); try { throw ex; } catch (Exception e) when (e switch { ArgumentException => true, _ => false }) { Console.WriteLine(""correct""); return; } } } "; var expectedOutput = "correct"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (7,23): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // static async Task Main() Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(7, 23)); var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [WorkItem(48563, "https://github.com/dotnet/roslyn/issues/48563")] [Theory] [InlineData("void*")] [InlineData("char*")] [InlineData("delegate*<void>")] public void IsNull_01(string pointerType) { var source = $@"using static System.Console; unsafe class Program {{ static void Main() {{ Check(0); Check(-1); }} static void Check(nint i) {{ {pointerType} p = ({pointerType})i; WriteLine(EqualNull(p)); WriteLine(IsNull(p)); WriteLine(NotEqualNull(p)); WriteLine(IsNotNull(p)); }} static bool EqualNull({pointerType} p) => p == null; static bool NotEqualNull({pointerType} p) => p != null; static bool IsNull({pointerType} p) => p is null; static bool IsNotNull({pointerType} p) => p is not null; }}"; var verifier = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: @"True True False False False False True True"); string expectedEqualNull = @"{ // Code size 6 (0x6) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: conv.u IL_0003: ceq IL_0005: ret }"; string expectedNotEqualNull = @"{ // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: conv.u IL_0003: ceq IL_0005: ldc.i4.0 IL_0006: ceq IL_0008: ret }"; verifier.VerifyIL("Program.EqualNull", expectedEqualNull); verifier.VerifyIL("Program.NotEqualNull", expectedNotEqualNull); verifier.VerifyIL("Program.IsNull", expectedEqualNull); verifier.VerifyIL("Program.IsNotNull", expectedNotEqualNull); } [WorkItem(48563, "https://github.com/dotnet/roslyn/issues/48563")] [Fact] public void IsNull_02() { var source = @"using static System.Console; unsafe class Program { static void Main() { Check(0); Check(-1); } static void Check(nint i) { char* p = (char*)i; WriteLine(EqualNull(p)); } static bool EqualNull(char* p) => p switch { null => true, _ => false }; }"; var verifier = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: @"True False"); verifier.VerifyIL("Program.EqualNull", @"{ // Code size 13 (0xd) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: conv.u IL_0003: bne.un.s IL_0009 IL_0005: ldc.i4.1 IL_0006: stloc.0 IL_0007: br.s IL_000b IL_0009: ldc.i4.0 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ret }"); } [WorkItem(48563, "https://github.com/dotnet/roslyn/issues/48563")] [Fact] public void IsNull_03() { var source = @"using static System.Console; unsafe class C { public char* P; } unsafe class Program { static void Main() { Check(0); Check(-1); } static void Check(nint i) { char* p = (char*)i; WriteLine(EqualNull(new C() { P = p })); } static bool EqualNull(C c) => c switch { { P: null } => true, _ => false }; }"; var verifier = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: @"True False"); verifier.VerifyIL("Program.EqualNull", @"{ // Code size 21 (0x15) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0011 IL_0003: ldarg.0 IL_0004: ldfld ""char* C.P"" IL_0009: ldc.i4.0 IL_000a: conv.u IL_000b: bne.un.s IL_0011 IL_000d: ldc.i4.1 IL_000e: stloc.0 IL_000f: br.s IL_0013 IL_0011: ldc.i4.0 IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ret }"); } #endregion Miscellaneous #region Target Typed Switch [Fact] public void TargetTypedSwitch_Assignment() { var source = @" using System; class Program { public static void Main() { Console.Write(M(false)); Console.Write(M(true)); } static object M(bool b) { int result = b switch { false => new A(), true => new B() }; return result; } } class A { public static implicit operator int(A a) => throw null; public static implicit operator B(A a) => new B(); } class B { public static implicit operator int(B b) => (b == null) ? throw null : 2; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"22"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void TargetTypedSwitch_Return() { var source = @" using System; class Program { public static void Main() { Console.Write(M(false)); Console.Write(M(true)); } static long M(bool b) { return b switch { false => new A(), true => new B() }; } } class A { public static implicit operator int(A a) => throw null; public static implicit operator B(A a) => new B(); } class B { public static implicit operator int(B b) => (b == null) ? throw null : 2; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"22"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void TargetTypedSwitch_Argument_01() { var source = @" using System; class Program { public static void Main() { Console.Write(M1(false)); Console.Write(M1(true)); } static object M1(bool b) { return M2(b switch { false => new A(), true => new B() }); } static Exception M2(Exception ex) => ex; static int M2(int i) => i; static int M2(string s) => s.Length; } class A : Exception { public static implicit operator int(A a) => throw null; public static implicit operator B(A a) => throw null; } class B : Exception { public static implicit operator int(B b) => throw null; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (12,16): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M2(Exception)' and 'Program.M2(int)' // return M2(b switch { false => new A(), true => new B() }); Diagnostic(ErrorCode.ERR_AmbigCall, "M2").WithArguments("Program.M2(System.Exception)", "Program.M2(int)").WithLocation(12, 16) ); } [Fact] public void TargetTypedSwitch_Argument_02() { var source = @" using System; class Program { public static void Main() { Console.Write(M1(false)); Console.Write(M1(true)); } static object M1(bool b) { return M2(b switch { false => new A(), true => new B() }); } // static Exception M2(Exception ex) => ex; static int M2(int i) => i; static int M2(string s) => s.Length; } class A : Exception { public static implicit operator int(A a) => throw null; public static implicit operator B(A a) => new B(); } class B : Exception { public static implicit operator int(B b) => (b == null) ? throw null : 2; } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"22"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void TargetTypedSwitch_Arglist() { var source = @" using System; class Program { public static void Main() { Console.WriteLine(M1(false)); Console.WriteLine(M1(true)); } static object M1(bool b) { return M2(__arglist(b switch { false => new A(), true => new B() })); } static int M2(__arglist) => 1; } class A { public A() { Console.Write(""new A; ""); } public static implicit operator B(A a) { Console.Write(""A->""); return new B(); } } class B { public B() { Console.Write(""new B; ""); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"new A; A->new B; 1 new B; 1"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void TargetTypedSwitch_StackallocSize() { var source = @" using System; class Program { public static void Main() { M1(false); M1(true); } static void M1(bool b) { Span<int> s = stackalloc int[b switch { false => new A(), true => new B() }]; Console.WriteLine(s.Length); } } class A { public A() { Console.Write(""new A; ""); } public static implicit operator int(A a) { Console.Write(""A->int; ""); return 4; } } class B { public B() { Console.Write(""new B; ""); } public static implicit operator int(B b) { Console.Write(""B->int; ""); return 2; } } "; var compilation = CreateCompilationWithMscorlibAndSpan(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @"new A; A->int; 4 new B; B->int; 2"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped); } [Fact] public void TargetTypedSwitch_Attribute() { var source = @" using System; class Program { [My(1 switch { 1 => 1, _ => 2 })] public static void M1() { } [My(1 switch { 1 => new A(), _ => new B() })] public static void M2() { } [My(1 switch { 1 => 1, _ => string.Empty })] public static void M3() { } } public class MyAttribute : Attribute { public MyAttribute(int Value) { } } public class A { public static implicit operator int(A a) => 4; } public class B { public static implicit operator int(B b) => 2; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (5,9): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(1 switch { 1 => 1, _ => 2 })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => 1, _ => 2 }").WithLocation(5, 9), // (8,9): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(1 switch { 1 => new A(), _ => new B() })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => new A(), _ => new B() }").WithLocation(8, 9), // (11,9): error CS1503: Argument 1: cannot convert from '<switch expression>' to 'int' // [My(1 switch { 1 => 1, _ => string.Empty })] Diagnostic(ErrorCode.ERR_BadArgType, "1 switch { 1 => 1, _ => string.Empty }").WithArguments("1", "<switch expression>", "int").WithLocation(11, 9) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var switchExpressions = tree.GetRoot().DescendantNodes().OfType<SwitchExpressionSyntax>().ToArray(); VerifyOperationTreeForNode(compilation, model, switchExpressions[0], @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... 1, _ => 2 }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => 1') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => 2') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') "); VerifyOperationTreeForNode(compilation, model, switchExpressions[1], @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... > new B() }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => new A()') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 A.op_Implicit(A a)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new A()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 A.op_Implicit(A a)) Operand: IObjectCreationOperation (Constructor: A..ctor()) (OperationKind.ObjectCreation, Type: A, IsInvalid) (Syntax: 'new A()') Arguments(0) Initializer: null ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => new B()') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 B.op_Implicit(B b)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new B()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 B.op_Implicit(B b)) Operand: IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B, IsInvalid) (Syntax: 'new B()') Arguments(0) Initializer: null "); VerifyOperationTreeForNode(compilation, model, switchExpressions[2], @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?, IsInvalid) (Syntax: '1 switch { ... ing.Empty }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => 1') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => string.Empty') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsInvalid, IsImplicit) (Syntax: 'string.Empty') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null "); } [Fact] public void TargetTypedSwitch_Attribute_NamedArgument() { var source = @" using System; class Program { [My(Value = 1 switch { 1 => 1, _ => 2 })] public static void M1() { } [My(Value = 1 switch { 1 => new A(), _ => new B() })] public static void M2() { } [My(Value = 1 switch { 1 => 1, _ => string.Empty })] public static void M3() { } } public class MyAttribute : Attribute { public MyAttribute() { } public int Value { get; set; } } public class A { public static implicit operator int(A a) => 4; } public class B { public static implicit operator int(B b) => 2; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (5,17): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(Value = 1 switch { 1 => 1, _ => 2 })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => 1, _ => 2 }").WithLocation(5, 17), // (8,17): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(Value = 1 switch { 1 => new A(), _ => new B() })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => new A(), _ => new B() }").WithLocation(8, 17), // (11,41): error CS0029: Cannot implicitly convert type 'string' to 'int' // [My(Value = 1 switch { 1 => 1, _ => string.Empty })] Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 41) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var attributeArguments = tree.GetRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().ToArray(); VerifyOperationTreeForNode(compilation, model, attributeArguments[0], @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'Value = 1 s ... 1, _ => 2 }') Left: IPropertyReferenceOperation: System.Int32 MyAttribute.Value { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Value') Instance Receiver: null Right: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... 1, _ => 2 }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => 1') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => 2') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') "); VerifyOperationTreeForNode(compilation, model, attributeArguments[1], @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'Value = 1 s ... > new B() }') Left: IPropertyReferenceOperation: System.Int32 MyAttribute.Value { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Value') Instance Receiver: null Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '1 switch { ... > new B() }') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... > new B() }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => new A()') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 A.op_Implicit(A a)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new A()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 A.op_Implicit(A a)) Operand: IObjectCreationOperation (Constructor: A..ctor()) (OperationKind.ObjectCreation, Type: A, IsInvalid) (Syntax: 'new A()') Arguments(0) Initializer: null ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => new B()') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 B.op_Implicit(B b)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new B()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 B.op_Implicit(B b)) Operand: IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B, IsInvalid) (Syntax: 'new B()') Arguments(0) Initializer: null "); VerifyOperationTreeForNode(compilation, model, attributeArguments[2], @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'Value = 1 s ... ing.Empty }') Left: IPropertyReferenceOperation: System.Int32 MyAttribute.Value { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Value') Instance Receiver: null Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '1 switch { ... ing.Empty }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?, IsInvalid) (Syntax: '1 switch { ... ing.Empty }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 1') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => string.Empty') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsInvalid, IsImplicit) (Syntax: 'string.Empty') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null "); } [Fact] public void TargetTypedSwitch_Attribute_MissingNamedArgument() { var source = @" using System; class Program { [My(Value = 1 switch { 1 => 1, _ => 2 })] public static void M1() { } [My(Value = 1 switch { 1 => new A(), _ => new B() })] public static void M2() { } [My(Value = 1 switch { 1 => 1, _ => string.Empty })] public static void M3() { } } public class MyAttribute : Attribute { public MyAttribute() { } } public class A { public static implicit operator int(A a) => 4; } public class B { public static implicit operator int(B b) => 2; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (5,9): error CS0246: The type or namespace name 'Value' could not be found (are you missing a using directive or an assembly reference?) // [My(Value = 1 switch { 1 => 1, _ => 2 })] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Value").WithArguments("Value").WithLocation(5, 9), // (8,9): error CS0246: The type or namespace name 'Value' could not be found (are you missing a using directive or an assembly reference?) // [My(Value = 1 switch { 1 => new A(), _ => new B() })] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Value").WithArguments("Value").WithLocation(8, 9), // (11,9): error CS0246: The type or namespace name 'Value' could not be found (are you missing a using directive or an assembly reference?) // [My(Value = 1 switch { 1 => 1, _ => string.Empty })] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Value").WithArguments("Value").WithLocation(11, 9) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var attributeArguments = tree.GetRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().ToArray(); VerifyOperationTreeForNode(compilation, model, attributeArguments[0], @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Value = 1 s ... 1, _ => 2 }') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Value') Children(0) Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1 switch { ... 1, _ => 2 }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32) (Syntax: '1 switch { ... 1, _ => 2 }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 1') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => 2') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "); VerifyOperationTreeForNode(compilation, model, attributeArguments[1], @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Value = 1 s ... > new B() }') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Value') Children(0) Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1 switch { ... > new B() }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?) (Syntax: '1 switch { ... > new B() }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => new A()') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: 'new A()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IObjectCreationOperation (Constructor: A..ctor()) (OperationKind.ObjectCreation, Type: A) (Syntax: 'new A()') Arguments(0) Initializer: null ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => new B()') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: 'new B()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B) (Syntax: 'new B()') Arguments(0) Initializer: null "); VerifyOperationTreeForNode(compilation, model, attributeArguments[2], @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Value = 1 s ... ing.Empty }') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Value') Children(0) Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1 switch { ... ing.Empty }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?) (Syntax: '1 switch { ... ing.Empty }') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 1') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => string.Empty') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: 'string.Empty') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "); } [Fact] public void TargetTypedSwitch_As() { var source = @" class Program { public static void M(int i, string s) { // we do not target-type the left-hand-side of an as expression _ = i switch { 1 => i, _ => s } as object; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,15): error CS8506: No best type was found for the switch expression. // _ = i switch { 1 => i, _ => s } as object; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(7, 15) ); } [Fact] public void TargetTypedSwitch_DoubleConversion() { var source = @"using System; class Program { public static void Main(string[] args) { M(false); M(true); } public static void M(bool b) { C c = b switch { false => new A(), true => new B() }; Console.WriteLine("".""); } } class A { public A() { Console.Write(""new A; ""); } public static implicit operator B(A a) { Console.Write(""A->""); return new B(); } } class B { public B() { Console.Write(""new B; ""); } public static implicit operator C(B a) { Console.Write(""B->""); return new C(); } } class C { public C() { Console.Write(""new C; ""); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var expectedOutput = @"new A; A->new B; B->new C; . new B; B->new C; ."; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void TargetTypedSwitch_StringInsert() { var source = @" using System; class Program { public static void Main() { Console.Write($""{false switch { false => new A(), true => new B() }}""); Console.Write($""{true switch { false => new A(), true => new B() }}""); } } class A { } class B { } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "AB"); } #endregion Target Typed Switch #region Pattern Combinators [Fact] public void IsPatternDisjunct_01() { var source = @" using System; class C { static bool M1(object o) => o is int or long; static bool M2(object o) => o is int || o is long; public static void Main() { Console.Write(M1(1)); Console.Write(M1(string.Empty)); Console.Write(M1(1L)); Console.Write(M1(1UL)); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); var expectedOutput = @"TrueFalseTrueFalse"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); var code = @" { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.0 IL_0001: isinst ""int"" IL_0006: brtrue.s IL_0013 IL_0008: ldarg.0 IL_0009: isinst ""long"" IL_000e: ldnull IL_000f: cgt.un IL_0011: br.s IL_0014 IL_0013: ldc.i4.1 IL_0014: ret } "; compVerifier.VerifyIL("C.M1", code); compVerifier.VerifyIL("C.M2", code); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); code = @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: isinst ""int"" IL_0006: brtrue.s IL_0012 IL_0008: ldarg.0 IL_0009: isinst ""long"" IL_000e: ldnull IL_000f: cgt.un IL_0011: ret IL_0012: ldc.i4.1 IL_0013: ret } "; compVerifier.VerifyIL("C.M1", code); compVerifier.VerifyIL("C.M2", code); } [Fact] public void IsPatternDisjunct_02() { var source = @" using System; class C { static string M1(object o) => (o is int or long) ? ""True"" : ""False""; static string M2(object o) => (o is int || o is long) ? ""True"" : ""False""; public static void Main() { Console.Write(M1(1)); Console.Write(M1(string.Empty)); Console.Write(M1(1L)); Console.Write(M1(1UL)); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); var expectedOutput = @"TrueFalseTrueFalse"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); var code = @" { // Code size 29 (0x1d) .maxstack 1 IL_0000: ldarg.0 IL_0001: isinst ""int"" IL_0006: brtrue.s IL_0017 IL_0008: ldarg.0 IL_0009: isinst ""long"" IL_000e: brtrue.s IL_0017 IL_0010: ldstr ""False"" IL_0015: br.s IL_001c IL_0017: ldstr ""True"" IL_001c: ret } "; compVerifier.VerifyIL("C.M1", code); compVerifier.VerifyIL("C.M2", code); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); code = @" { // Code size 28 (0x1c) .maxstack 1 IL_0000: ldarg.0 IL_0001: isinst ""int"" IL_0006: brtrue.s IL_0016 IL_0008: ldarg.0 IL_0009: isinst ""long"" IL_000e: brtrue.s IL_0016 IL_0010: ldstr ""False"" IL_0015: ret IL_0016: ldstr ""True"" IL_001b: ret } "; compVerifier.VerifyIL("C.M1", code); compVerifier.VerifyIL("C.M2", code); } [Fact] public void IsPatternDisjunct_03() { var source = @" using System; class C { static bool M1(object o) => o is >= 'A' and <= 'Z' or >= 'a' and <= 'z'; static bool M2(object o) => o is char c && (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'); public static void Main() { Console.Write(M1('A')); Console.Write(M1('0')); Console.Write(M1('q')); Console.Write(M1(2)); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); var expectedOutput = @"TrueFalseTrueFalse"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (char V_0, bool V_1) IL_0000: ldarg.0 IL_0001: isinst ""char"" IL_0006: brfalse.s IL_002b IL_0008: ldarg.0 IL_0009: unbox.any ""char"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: ldc.i4.s 97 IL_0012: blt.s IL_001b IL_0014: ldloc.0 IL_0015: ldc.i4.s 122 IL_0017: ble.s IL_0027 IL_0019: br.s IL_002b IL_001b: ldloc.0 IL_001c: ldc.i4.s 65 IL_001e: blt.s IL_002b IL_0020: ldloc.0 IL_0021: ldc.i4.s 90 IL_0023: ble.s IL_0027 IL_0025: br.s IL_002b IL_0027: ldc.i4.1 IL_0028: stloc.1 IL_0029: br.s IL_002d IL_002b: ldc.i4.0 IL_002c: stloc.1 IL_002d: ldloc.1 IL_002e: ret } "); compVerifier.VerifyIL("C.M2", @" { // Code size 48 (0x30) .maxstack 2 .locals init (char V_0) //c IL_0000: ldarg.0 IL_0001: isinst ""char"" IL_0006: brfalse.s IL_002e IL_0008: ldarg.0 IL_0009: unbox.any ""char"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: ldc.i4.s 65 IL_0012: blt.s IL_0019 IL_0014: ldloc.0 IL_0015: ldc.i4.s 90 IL_0017: ble.s IL_002b IL_0019: ldloc.0 IL_001a: ldc.i4.s 97 IL_001c: blt.s IL_0028 IL_001e: ldloc.0 IL_001f: ldc.i4.s 122 IL_0021: cgt IL_0023: ldc.i4.0 IL_0024: ceq IL_0026: br.s IL_0029 IL_0028: ldc.i4.0 IL_0029: br.s IL_002c IL_002b: ldc.i4.1 IL_002c: br.s IL_002f IL_002e: ldc.i4.0 IL_002f: ret } "); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @" { // Code size 45 (0x2d) .maxstack 2 .locals init (char V_0, bool V_1) IL_0000: ldarg.0 IL_0001: isinst ""char"" IL_0006: brfalse.s IL_0029 IL_0008: ldarg.0 IL_0009: unbox.any ""char"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: ldc.i4.s 97 IL_0012: blt.s IL_001b IL_0014: ldloc.0 IL_0015: ldc.i4.s 122 IL_0017: ble.s IL_0025 IL_0019: br.s IL_0029 IL_001b: ldloc.0 IL_001c: ldc.i4.s 65 IL_001e: blt.s IL_0029 IL_0020: ldloc.0 IL_0021: ldc.i4.s 90 IL_0023: bgt.s IL_0029 IL_0025: ldc.i4.1 IL_0026: stloc.1 IL_0027: br.s IL_002b IL_0029: ldc.i4.0 IL_002a: stloc.1 IL_002b: ldloc.1 IL_002c: ret } "); compVerifier.VerifyIL("C.M2", @" { // Code size 45 (0x2d) .maxstack 2 .locals init (char V_0) //c IL_0000: ldarg.0 IL_0001: isinst ""char"" IL_0006: brfalse.s IL_002b IL_0008: ldarg.0 IL_0009: unbox.any ""char"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: ldc.i4.s 65 IL_0012: blt.s IL_0019 IL_0014: ldloc.0 IL_0015: ldc.i4.s 90 IL_0017: ble.s IL_0029 IL_0019: ldloc.0 IL_001a: ldc.i4.s 97 IL_001c: blt.s IL_0027 IL_001e: ldloc.0 IL_001f: ldc.i4.s 122 IL_0021: cgt IL_0023: ldc.i4.0 IL_0024: ceq IL_0026: ret IL_0027: ldc.i4.0 IL_0028: ret IL_0029: ldc.i4.1 IL_002a: ret IL_002b: ldc.i4.0 IL_002c: ret } "); } [Fact] public void IsPatternDisjunct_04() { var source = @" using System; class C { static int M1(char c) => (c is >= 'A' and <= 'Z' or >= 'a' and <= 'z') ? 1 : 0; static int M2(char c) => (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') ? 1 : 0; public static void Main() { Console.Write(M1('A')); Console.Write(M1('0')); Console.Write(M1('q')); Console.Write(M1(' ')); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); var expectedOutput = @"1010"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @" { // Code size 38 (0x26) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.s 97 IL_0003: blt.s IL_000c IL_0005: ldarg.0 IL_0006: ldc.i4.s 122 IL_0008: ble.s IL_0018 IL_000a: br.s IL_001c IL_000c: ldarg.0 IL_000d: ldc.i4.s 65 IL_000f: blt.s IL_001c IL_0011: ldarg.0 IL_0012: ldc.i4.s 90 IL_0014: ble.s IL_0018 IL_0016: br.s IL_001c IL_0018: ldc.i4.1 IL_0019: stloc.0 IL_001a: br.s IL_001e IL_001c: ldc.i4.0 IL_001d: stloc.0 IL_001e: ldloc.0 IL_001f: brtrue.s IL_0024 IL_0021: ldc.i4.0 IL_0022: br.s IL_0025 IL_0024: ldc.i4.1 IL_0025: ret } "); compVerifier.VerifyIL("C.M2", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 65 IL_0003: blt.s IL_000a IL_0005: ldarg.0 IL_0006: ldc.i4.s 90 IL_0008: ble.s IL_0017 IL_000a: ldarg.0 IL_000b: ldc.i4.s 97 IL_000d: blt.s IL_0014 IL_000f: ldarg.0 IL_0010: ldc.i4.s 122 IL_0012: ble.s IL_0017 IL_0014: ldc.i4.0 IL_0015: br.s IL_0018 IL_0017: ldc.i4.1 IL_0018: ret } "); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @" { // Code size 35 (0x23) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.s 97 IL_0003: blt.s IL_000c IL_0005: ldarg.0 IL_0006: ldc.i4.s 122 IL_0008: ble.s IL_0016 IL_000a: br.s IL_001a IL_000c: ldarg.0 IL_000d: ldc.i4.s 65 IL_000f: blt.s IL_001a IL_0011: ldarg.0 IL_0012: ldc.i4.s 90 IL_0014: bgt.s IL_001a IL_0016: ldc.i4.1 IL_0017: stloc.0 IL_0018: br.s IL_001c IL_001a: ldc.i4.0 IL_001b: stloc.0 IL_001c: ldloc.0 IL_001d: brtrue.s IL_0021 IL_001f: ldc.i4.0 IL_0020: ret IL_0021: ldc.i4.1 IL_0022: ret } "); compVerifier.VerifyIL("C.M2", @" { // Code size 24 (0x18) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 65 IL_0003: blt.s IL_000a IL_0005: ldarg.0 IL_0006: ldc.i4.s 90 IL_0008: ble.s IL_0016 IL_000a: ldarg.0 IL_000b: ldc.i4.s 97 IL_000d: blt.s IL_0014 IL_000f: ldarg.0 IL_0010: ldc.i4.s 122 IL_0012: ble.s IL_0016 IL_0014: ldc.i4.0 IL_0015: ret IL_0016: ldc.i4.1 IL_0017: ret } "); } [Fact] public void IsPatternDisjunct_05() { var source = @" using System; class C { static int M1(char c) { if (c is >= 'A' and <= 'Z' or >= 'a' and <= 'z') return 1; else return 0; } static int M2(char c) { if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') return 1; else return 0; } public static void Main() { Console.Write(M1('A')); Console.Write(M1('0')); Console.Write(M1('q')); Console.Write(M1(' ')); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); var expectedOutput = @"1010"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (bool V_0, bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.s 97 IL_0004: blt.s IL_000d IL_0006: ldarg.0 IL_0007: ldc.i4.s 122 IL_0009: ble.s IL_0019 IL_000b: br.s IL_001d IL_000d: ldarg.0 IL_000e: ldc.i4.s 65 IL_0010: blt.s IL_001d IL_0012: ldarg.0 IL_0013: ldc.i4.s 90 IL_0015: ble.s IL_0019 IL_0017: br.s IL_001d IL_0019: ldc.i4.1 IL_001a: stloc.0 IL_001b: br.s IL_001f IL_001d: ldc.i4.0 IL_001e: stloc.0 IL_001f: ldloc.0 IL_0020: stloc.1 IL_0021: ldloc.1 IL_0022: brfalse.s IL_0028 IL_0024: ldc.i4.1 IL_0025: stloc.2 IL_0026: br.s IL_002c IL_0028: ldc.i4.0 IL_0029: stloc.2 IL_002a: br.s IL_002c IL_002c: ldloc.2 IL_002d: ret } "); compVerifier.VerifyIL("C.M2", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (bool V_0, int V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.s 65 IL_0004: blt.s IL_000b IL_0006: ldarg.0 IL_0007: ldc.i4.s 90 IL_0009: ble.s IL_001d IL_000b: ldarg.0 IL_000c: ldc.i4.s 97 IL_000e: blt.s IL_001a IL_0010: ldarg.0 IL_0011: ldc.i4.s 122 IL_0013: cgt IL_0015: ldc.i4.0 IL_0016: ceq IL_0018: br.s IL_001b IL_001a: ldc.i4.0 IL_001b: br.s IL_001e IL_001d: ldc.i4.1 IL_001e: stloc.0 IL_001f: ldloc.0 IL_0020: brfalse.s IL_0026 IL_0022: ldc.i4.1 IL_0023: stloc.1 IL_0024: br.s IL_002a IL_0026: ldc.i4.0 IL_0027: stloc.1 IL_0028: br.s IL_002a IL_002a: ldloc.1 IL_002b: ret } "); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators); compilation.VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M1", @" { // Code size 35 (0x23) .maxstack 2 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.s 97 IL_0003: blt.s IL_000c IL_0005: ldarg.0 IL_0006: ldc.i4.s 122 IL_0008: ble.s IL_0016 IL_000a: br.s IL_001a IL_000c: ldarg.0 IL_000d: ldc.i4.s 65 IL_000f: blt.s IL_001a IL_0011: ldarg.0 IL_0012: ldc.i4.s 90 IL_0014: bgt.s IL_001a IL_0016: ldc.i4.1 IL_0017: stloc.0 IL_0018: br.s IL_001c IL_001a: ldc.i4.0 IL_001b: stloc.0 IL_001c: ldloc.0 IL_001d: brfalse.s IL_0021 IL_001f: ldc.i4.1 IL_0020: ret IL_0021: ldc.i4.0 IL_0022: ret } "); compVerifier.VerifyIL("C.M2", @" { // Code size 24 (0x18) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 65 IL_0003: blt.s IL_000a IL_0005: ldarg.0 IL_0006: ldc.i4.s 90 IL_0008: ble.s IL_0014 IL_000a: ldarg.0 IL_000b: ldc.i4.s 97 IL_000d: blt.s IL_0016 IL_000f: ldarg.0 IL_0010: ldc.i4.s 122 IL_0012: bgt.s IL_0016 IL_0014: ldc.i4.1 IL_0015: ret IL_0016: ldc.i4.0 IL_0017: ret } "); } [Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")] public void MultiplePathsToNode_SwitchDispatch_01() { var source = @" using System; class Program { static void Main() { Console.Write(M("""", 0)); // 0 Console.Write(M("""", 1)); // 1 Console.Write(M("""", 2)); // 2 Console.Write(M("""", 3)); // 3 Console.Write(M(""a"", 2)); // 2 Console.Write(M(""a"", 10)); // 3 } static int M(string x, int y) { return (x, y) switch { ("""", 0) => 0, ("""", 1) => 1, (_, 2) => 2, _ => 3 }; } } "; var verifier = CompileAndVerify(source, expectedOutput: "012323", options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); verifier.VerifyIL("Program.M", @"{ // Code size 70 (0x46) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: ldstr """" IL_000b: call ""bool string.op_Equality(string, string)"" IL_0010: brfalse.s IL_0026 IL_0012: ldarg.1 IL_0013: switch ( IL_002c, IL_0030, IL_0034) IL_0024: br.s IL_0038 IL_0026: ldarg.1 IL_0027: ldc.i4.2 IL_0028: beq.s IL_0034 IL_002a: br.s IL_0038 IL_002c: ldc.i4.0 IL_002d: stloc.0 IL_002e: br.s IL_003c IL_0030: ldc.i4.1 IL_0031: stloc.0 IL_0032: br.s IL_003c IL_0034: ldc.i4.2 IL_0035: stloc.0 IL_0036: br.s IL_003c IL_0038: ldc.i4.3 IL_0039: stloc.0 IL_003a: br.s IL_003c IL_003c: ldc.i4.1 IL_003d: brtrue.s IL_0040 IL_003f: nop IL_0040: ldloc.0 IL_0041: stloc.1 IL_0042: br.s IL_0044 IL_0044: ldloc.1 IL_0045: ret }"); } [Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")] public void MultiplePathsToNode_SwitchDispatch_02() { var source = @" using System; class Program { static void Main() { Console.Write(M0("""", 0)); // 0 Console.Write(M0("""", 1)); // 1 Console.Write(M0("""", 2)); // 2 Console.Write(M0("""", 3)); // 3 Console.Write(M0(""a"", 2)); // 2 Console.Write(M0(""a"", 10)); // 3 } static int M0(string x, int y) { return (x, y) switch { ("""", 0) => M1(0), ("""", 1) => M1(1), (_, 2) => M1(2), _ => M1(3) }; } static int M1(int z) { Console.Write(' '); return z; } } "; var verifier = CompileAndVerify(source, expectedOutput: " 0 1 2 3 2 3", options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); verifier.VerifyIL("Program.M0", @"{ // Code size 90 (0x5a) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: ldstr """" IL_000b: call ""bool string.op_Equality(string, string)"" IL_0010: brfalse.s IL_0026 IL_0012: ldarg.1 IL_0013: switch ( IL_002c, IL_0035, IL_003e) IL_0024: br.s IL_0047 IL_0026: ldarg.1 IL_0027: ldc.i4.2 IL_0028: beq.s IL_003e IL_002a: br.s IL_0047 IL_002c: ldc.i4.0 IL_002d: call ""int Program.M1(int)"" IL_0032: stloc.0 IL_0033: br.s IL_0050 IL_0035: ldc.i4.1 IL_0036: call ""int Program.M1(int)"" IL_003b: stloc.0 IL_003c: br.s IL_0050 IL_003e: ldc.i4.2 IL_003f: call ""int Program.M1(int)"" IL_0044: stloc.0 IL_0045: br.s IL_0050 IL_0047: ldc.i4.3 IL_0048: call ""int Program.M1(int)"" IL_004d: stloc.0 IL_004e: br.s IL_0050 IL_0050: ldc.i4.1 IL_0051: brtrue.s IL_0054 IL_0053: nop IL_0054: ldloc.0 IL_0055: stloc.1 IL_0056: br.s IL_0058 IL_0058: ldloc.1 IL_0059: ret }"); } [Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")] public void MultiplePathsToNode_SwitchDispatch_03() { var source = @" using System; class Program { static void Main() { Console.Write(M("""", 0)); // 0 Console.Write(M("""", 1)); // 1 Console.Write(M("""", 2)); // 2 Console.Write(M("""", 3)); // 3 Console.Write(M("""", 4)); // 4 Console.Write(M("""", 5)); // 5 Console.Write(M(""a"", 2)); // 2 Console.Write(M(""a"", 3)); // 3 Console.Write(M(""a"", 4)); // 4 Console.Write(M(""a"", 10)); // 5 } static int M(string x, int y) { return (x, y) switch { ("""", 0) => 0, ("""", 1) => 1, (_, 2) => 2, (_, 3) => 3, (_, 4) => 4, _ => 5 }; } } "; var verifier = CompileAndVerify(source, expectedOutput: "0123452345", options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); verifier.VerifyIL("Program.M", @"{ // Code size 98 (0x62) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: ldstr """" IL_000b: call ""bool string.op_Equality(string, string)"" IL_0010: brfalse.s IL_002e IL_0012: ldarg.1 IL_0013: switch ( IL_0040, IL_0044, IL_0048, IL_004c, IL_0050) IL_002c: br.s IL_0054 IL_002e: ldarg.1 IL_002f: ldc.i4.2 IL_0030: beq.s IL_0048 IL_0032: br.s IL_0034 IL_0034: ldarg.1 IL_0035: ldc.i4.3 IL_0036: beq.s IL_004c IL_0038: br.s IL_003a IL_003a: ldarg.1 IL_003b: ldc.i4.4 IL_003c: beq.s IL_0050 IL_003e: br.s IL_0054 IL_0040: ldc.i4.0 IL_0041: stloc.0 IL_0042: br.s IL_0058 IL_0044: ldc.i4.1 IL_0045: stloc.0 IL_0046: br.s IL_0058 IL_0048: ldc.i4.2 IL_0049: stloc.0 IL_004a: br.s IL_0058 IL_004c: ldc.i4.3 IL_004d: stloc.0 IL_004e: br.s IL_0058 IL_0050: ldc.i4.4 IL_0051: stloc.0 IL_0052: br.s IL_0058 IL_0054: ldc.i4.5 IL_0055: stloc.0 IL_0056: br.s IL_0058 IL_0058: ldc.i4.1 IL_0059: brtrue.s IL_005c IL_005b: nop IL_005c: ldloc.0 IL_005d: stloc.1 IL_005e: br.s IL_0060 IL_0060: ldloc.1 IL_0061: ret }"); } [Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")] public void MultiplePathsToNode_SwitchDispatch_04() { var source = @" using System; class Program { static void Main() { Console.Write(M(""a"", ""x"")); // 0 Console.Write(M(""a"", ""y"")); // 1 Console.Write(M(""a"", ""z"")); // 2 Console.Write(M(""a"", ""w"")); // 3 Console.Write(M(""b"", ""z"")); // 2 Console.Write(M(""c"", ""z"")); // 3 Console.Write(M(""c"", ""w"")); // 3 } static int M(string x, string y) { return (x, y) switch { (""a"", ""x"") => 0, (""a"", ""y"") => 1, (""a"" or ""b"", ""z"") => 2, _ => 3 }; } } "; var verifier = CompileAndVerify(source, expectedOutput: "0123233", options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); verifier.VerifyDiagnostics(); verifier.VerifyIL("Program.M", @"{ // Code size 115 (0x73) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: ldstr ""a"" IL_000b: call ""bool string.op_Equality(string, string)"" IL_0010: brtrue.s IL_0021 IL_0012: ldarg.0 IL_0013: ldstr ""b"" IL_0018: call ""bool string.op_Equality(string, string)"" IL_001d: brtrue.s IL_004a IL_001f: br.s IL_0065 IL_0021: ldarg.1 IL_0022: ldstr ""z"" IL_0027: call ""bool string.op_Equality(string, string)"" IL_002c: brtrue.s IL_0061 IL_002e: ldarg.1 IL_002f: ldstr ""x"" IL_0034: call ""bool string.op_Equality(string, string)"" IL_0039: brtrue.s IL_0059 IL_003b: ldarg.1 IL_003c: ldstr ""y"" IL_0041: call ""bool string.op_Equality(string, string)"" IL_0046: brtrue.s IL_005d IL_0048: br.s IL_0065 IL_004a: ldarg.1 IL_004b: ldstr ""z"" IL_0050: call ""bool string.op_Equality(string, string)"" IL_0055: brtrue.s IL_0061 IL_0057: br.s IL_0065 IL_0059: ldc.i4.0 IL_005a: stloc.0 IL_005b: br.s IL_0069 IL_005d: ldc.i4.1 IL_005e: stloc.0 IL_005f: br.s IL_0069 IL_0061: ldc.i4.2 IL_0062: stloc.0 IL_0063: br.s IL_0069 IL_0065: ldc.i4.3 IL_0066: stloc.0 IL_0067: br.s IL_0069 IL_0069: ldc.i4.1 IL_006a: brtrue.s IL_006d IL_006c: nop IL_006d: ldloc.0 IL_006e: stloc.1 IL_006f: br.s IL_0071 IL_0071: ldloc.1 IL_0072: ret }"); } [Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")] public void MultiplePathsToNode_SwitchDispatch_05() { var source = @" using System; public enum EnumA { A, B, C } public enum EnumB { X, Y, Z } public class Class1 { public string Repro(EnumA a, EnumB b) => (a, b) switch { (EnumA.A, EnumB.X) => ""AX"", (_, EnumB.Y) => ""_Y"", (EnumA.B, EnumB.X) => ""BZ"", (_, EnumB.Z) => ""_Z"", (_, _) => throw new ArgumentException() }; } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugDll); verifier.VerifyDiagnostics(); verifier.VerifyIL("Class1.Repro", @"{ // Code size 90 (0x5a) .maxstack 2 .locals init (string V_0) IL_0000: ldc.i4.1 IL_0001: brtrue.s IL_0004 IL_0003: nop IL_0004: ldarg.1 IL_0005: brtrue.s IL_001b IL_0007: ldarg.2 IL_0008: switch ( IL_002e, IL_0036, IL_0046) IL_0019: br.s IL_004e IL_001b: ldarg.2 IL_001c: ldc.i4.1 IL_001d: beq.s IL_0036 IL_001f: ldarg.1 IL_0020: ldc.i4.1 IL_0021: bne.un.s IL_0028 IL_0023: ldarg.2 IL_0024: brfalse.s IL_003e IL_0026: br.s IL_0028 IL_0028: ldarg.2 IL_0029: ldc.i4.2 IL_002a: beq.s IL_0046 IL_002c: br.s IL_004e IL_002e: ldstr ""AX"" IL_0033: stloc.0 IL_0034: br.s IL_0054 IL_0036: ldstr ""_Y"" IL_003b: stloc.0 IL_003c: br.s IL_0054 IL_003e: ldstr ""BZ"" IL_0043: stloc.0 IL_0044: br.s IL_0054 IL_0046: ldstr ""_Z"" IL_004b: stloc.0 IL_004c: br.s IL_0054 IL_004e: newobj ""System.ArgumentException..ctor()"" IL_0053: throw IL_0054: ldc.i4.1 IL_0055: brtrue.s IL_0058 IL_0057: nop IL_0058: ldloc.0 IL_0059: ret }"); } #endregion Pattern Combinators } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Impl/Options/Style/BooleanCodeStyleOptionViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// This class represents the view model for a <see cref="CodeStyleOption{T}"/> /// that binds to the codestyle options UI. /// </summary> internal class BooleanCodeStyleOptionViewModel : AbstractCodeStyleOptionViewModel { private readonly string _truePreview; private readonly string _falsePreview; private CodeStylePreference _selectedPreference; private NotificationOptionViewModel _selectedNotificationPreference; public BooleanCodeStyleOptionViewModel( IOption option, string description, string truePreview, string falsePreview, AbstractOptionPreviewViewModel info, OptionStore optionStore, string groupName, List<CodeStylePreference> preferences = null, List<NotificationOptionViewModel> notificationPreferences = null) : base(option, description, info, groupName, preferences, notificationPreferences) { _truePreview = truePreview; _falsePreview = falsePreview; var codeStyleOption = ((CodeStyleOption<bool>)optionStore.GetOption(new OptionKey(option, option.IsPerLanguage ? info.Language : null))); _selectedPreference = Preferences.Single(c => c.IsChecked == codeStyleOption.Value); var notificationViewModel = NotificationPreferences.Single(i => i.Notification.Severity == codeStyleOption.Notification.Severity); _selectedNotificationPreference = NotificationPreferences.Single(p => p.Notification.Severity == notificationViewModel.Notification.Severity); NotifyPropertyChanged(nameof(SelectedPreference)); NotifyPropertyChanged(nameof(SelectedNotificationPreference)); } public override CodeStylePreference SelectedPreference { get => _selectedPreference; set { if (SetProperty(ref _selectedPreference, value)) { Info.SetOptionAndUpdatePreview(new CodeStyleOption<bool>(_selectedPreference.IsChecked, _selectedNotificationPreference.Notification), Option, GetPreview()); } } } public override NotificationOptionViewModel SelectedNotificationPreference { get => _selectedNotificationPreference; set { if (SetProperty(ref _selectedNotificationPreference, value)) { Info.SetOptionAndUpdatePreview(new CodeStyleOption<bool>(_selectedPreference.IsChecked, _selectedNotificationPreference.Notification), Option, GetPreview()); } } } public override string GetPreview() => SelectedPreference.IsChecked ? _truePreview : _falsePreview; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// This class represents the view model for a <see cref="CodeStyleOption{T}"/> /// that binds to the codestyle options UI. /// </summary> internal class BooleanCodeStyleOptionViewModel : AbstractCodeStyleOptionViewModel { private readonly string _truePreview; private readonly string _falsePreview; private CodeStylePreference _selectedPreference; private NotificationOptionViewModel _selectedNotificationPreference; public BooleanCodeStyleOptionViewModel( IOption option, string description, string truePreview, string falsePreview, AbstractOptionPreviewViewModel info, OptionStore optionStore, string groupName, List<CodeStylePreference> preferences = null, List<NotificationOptionViewModel> notificationPreferences = null) : base(option, description, info, groupName, preferences, notificationPreferences) { _truePreview = truePreview; _falsePreview = falsePreview; var codeStyleOption = ((CodeStyleOption<bool>)optionStore.GetOption(new OptionKey(option, option.IsPerLanguage ? info.Language : null))); _selectedPreference = Preferences.Single(c => c.IsChecked == codeStyleOption.Value); var notificationViewModel = NotificationPreferences.Single(i => i.Notification.Severity == codeStyleOption.Notification.Severity); _selectedNotificationPreference = NotificationPreferences.Single(p => p.Notification.Severity == notificationViewModel.Notification.Severity); NotifyPropertyChanged(nameof(SelectedPreference)); NotifyPropertyChanged(nameof(SelectedNotificationPreference)); } public override CodeStylePreference SelectedPreference { get => _selectedPreference; set { if (SetProperty(ref _selectedPreference, value)) { Info.SetOptionAndUpdatePreview(new CodeStyleOption<bool>(_selectedPreference.IsChecked, _selectedNotificationPreference.Notification), Option, GetPreview()); } } } public override NotificationOptionViewModel SelectedNotificationPreference { get => _selectedNotificationPreference; set { if (SetProperty(ref _selectedNotificationPreference, value)) { Info.SetOptionAndUpdatePreview(new CodeStyleOption<bool>(_selectedPreference.IsChecked, _selectedNotificationPreference.Notification), Option, GetPreview()); } } } public override string GetPreview() => SelectedPreference.IsChecked ? _truePreview : _falsePreview; } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/Binder/AliasAndExternAliasDirective.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal struct AliasAndExternAliasDirective { public readonly AliasSymbol Alias; public readonly SyntaxReference? ExternAliasDirectiveReference; public readonly bool SkipInLookup; public AliasAndExternAliasDirective(AliasSymbol alias, ExternAliasDirectiveSyntax? externAliasDirective, bool skipInLookup) { this.Alias = alias; this.ExternAliasDirectiveReference = externAliasDirective?.GetReference(); this.SkipInLookup = skipInLookup; } public ExternAliasDirectiveSyntax? ExternAliasDirective => (ExternAliasDirectiveSyntax?)ExternAliasDirectiveReference?.GetSyntax(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal struct AliasAndExternAliasDirective { public readonly AliasSymbol Alias; public readonly SyntaxReference? ExternAliasDirectiveReference; public readonly bool SkipInLookup; public AliasAndExternAliasDirective(AliasSymbol alias, ExternAliasDirectiveSyntax? externAliasDirective, bool skipInLookup) { this.Alias = alias; this.ExternAliasDirectiveReference = externAliasDirective?.GetReference(); this.SkipInLookup = skipInLookup; } public ExternAliasDirectiveSyntax? ExternAliasDirective => (ExternAliasDirectiveSyntax?)ExternAliasDirectiveReference?.GetSyntax(); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Test/GenerateType/GenerateTypeViewModelTests.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.IO Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.GenerateType Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.ProjectManagement Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.GenerateType <[UseExportProvider]> Public Class GenerateTypeViewModelTests Private Shared ReadOnly s_assembly1_Name As String = "Assembly1" Private Shared ReadOnly s_test1_Name As String = "Test1" Private Shared ReadOnly s_submit_failed_unexpectedly As String = "Submit failed unexpectedly." Private Shared ReadOnly s_submit_passed_unexpectedly As String = "Submit passed unexpectedly. Submit should fail here" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeExistingFileCSharp() As Task Dim documentContentMarkup = <Text><![CDATA[ class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, "C#") ' Test the default values Assert.Equal(0, viewModel.AccessSelectIndex) Assert.Equal(0, viewModel.KindSelectIndex) Assert.Equal("Goo", viewModel.TypeName) Assert.Equal("Goo.cs", viewModel.FileName) Assert.Equal(s_assembly1_Name, viewModel.SelectedProject.Name) Assert.Equal(s_test1_Name + ".cs", viewModel.SelectedDocument.Name) Assert.Equal(True, viewModel.IsExistingFile) ' Set the Radio to new file viewModel.IsNewFile = True Assert.Equal(True, viewModel.IsNewFile) Assert.Equal(False, viewModel.IsExistingFile) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeExistingFileVisualBasic() As Task Dim documentContentMarkup = <Text><![CDATA[ Module Program Sub Main(args As String()) Dim x As A.B.Goo$$ = Nothing End Sub End Module Namespace A Namespace B End Namespace End Namespace"]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, "Visual Basic") ' Test the default values Assert.Equal(0, viewModel.AccessSelectIndex) Assert.Equal(0, viewModel.KindSelectIndex) Assert.Equal("Goo", viewModel.TypeName) Assert.Equal("Goo.vb", viewModel.FileName) Assert.Equal(s_assembly1_Name, viewModel.SelectedProject.Name) Assert.Equal(s_test1_Name + ".vb", viewModel.SelectedDocument.Name) Assert.Equal(True, viewModel.IsExistingFile) ' Set the Radio to new file viewModel.IsNewFile = True Assert.Equal(True, viewModel.IsNewFile) Assert.Equal(False, viewModel.IsExistingFile) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeNewFileBothLanguage() As Task Dim documentContentMarkup = <Text><![CDATA[ class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, "C#", projectRootFilePath:="C:\OuterFolder\InnerFolder\") viewModel.IsNewFile = True ' Feed a filename and check if the change is effective viewModel.FileName = "Wow" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.Equal("Wow.cs", viewModel.FileName) viewModel.FileName = "Goo\Bar\Woow" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.Equal("Woow.cs", viewModel.FileName) Assert.Equal(2, viewModel.Folders.Count) Assert.Equal("Goo", viewModel.Folders(0)) Assert.Equal("Bar", viewModel.Folders(1)) viewModel.FileName = "\ name has space \ Goo \Bar\ Woow" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.Equal("Woow.cs", viewModel.FileName) Assert.Equal(3, viewModel.Folders.Count) Assert.Equal("name has space", viewModel.Folders(0)) Assert.Equal("Goo", viewModel.Folders(1)) Assert.Equal("Bar", viewModel.Folders(2)) ' Set it to invalid identifier viewModel.FileName = "w?d" viewModel.UpdateFileNameExtension() Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) viewModel.FileName = "wow\w?d" viewModel.UpdateFileNameExtension() Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) viewModel.FileName = "w?d\wdd" viewModel.UpdateFileNameExtension() Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeProjectChangeAndDependencyBothLanguage() As Task Dim workspaceXml = <Workspace> <Project Language="C#" AssemblyName="CS1" CommonReferences="true"> <Document FilePath="Test1.cs"> class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } } </Document> <Document FilePath="Test4.cs"></Document> </Project> <Project Language="C#" AssemblyName="CS2" CommonReferences="true"> <ProjectReference>CS1</ProjectReference> </Project> <Project Language="C#" AssemblyName="CS3" CommonReferences="true"> <ProjectReference>CS2</ProjectReference> </Project> <Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true"> <Document FilePath="Test2.vb"></Document> <Document FilePath="Test3.vb"></Document> </Project> </Workspace> Dim viewModel = Await GetViewModelAsync(workspaceXml, "") ' Only 2 Projects can be selected because CS2 and CS3 will introduce cyclic dependency Assert.Equal(2, viewModel.ProjectList.Count) Assert.Equal(2, viewModel.DocumentList.Count()) viewModel.DocumentSelectIndex = 1 Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project Dim monitor = New PropertyChangedTestMonitor(viewModel) ' Check to see if the values are reset when there is a change in the project selection viewModel.SelectedProject = projectToSelect Assert.Equal(2, viewModel.DocumentList.Count()) Assert.Equal(0, viewModel.DocumentSelectIndex) Assert.Equal(1, viewModel.ProjectSelectIndex) monitor.VerifyExpectations() monitor.Detach() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeDisableExistingFileForEmptyProject() As Task Dim workspaceXml = <Workspace> <Project Language="C#" AssemblyName="CS1" CommonReferences="true"> <Document FilePath="Test1.cs"> class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } } </Document> <Document FilePath="Test4.cs"></Document> </Project> <Project Language="C#" AssemblyName="CS2" CommonReferences="true"/> </Workspace> Dim viewModel = Await GetViewModelAsync(workspaceXml, "") ' Select the project CS2 which has no documents. Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS2").Single().Project viewModel.SelectedProject = projectToSelect ' Check if the option for Existing File is disabled Assert.Equal(0, viewModel.DocumentList.Count()) Assert.Equal(False, viewModel.IsExistingFileEnabled) ' Select the project CS1 which has documents projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project viewModel.SelectedProject = projectToSelect ' Check if the option for Existing File is enabled Assert.Equal(2, viewModel.DocumentList.Count()) Assert.Equal(True, viewModel.IsExistingFileEnabled) End Function <WorkItem(858815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858815")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeAllowPublicAccessOnlyForGenerationIntoOtherProject() As Task Dim workspaceXml = <Workspace> <Project Language="C#" AssemblyName="CS1" CommonReferences="true"> <Document FilePath="Test1.cs"> class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } } </Document> <Document FilePath="Test4.cs"></Document> </Project> <Project Language="C#" AssemblyName="CS2" CommonReferences="true"/> </Workspace> Dim viewModel = Await GetViewModelAsync(workspaceXml, "") viewModel.SelectedAccessibilityString = "Default" ' Check if the AccessKind List is enabled Assert.Equal(True, viewModel.IsAccessListEnabled) ' Select the project CS2 which has no documents. Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS2").Single().Project viewModel.SelectedProject = projectToSelect ' Check if access kind is set to Public and the AccessKind is set to be disabled Assert.Equal(2, viewModel.AccessSelectIndex) Assert.Equal(False, viewModel.IsAccessListEnabled) ' Switch back to the initial document projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project viewModel.SelectedProject = projectToSelect ' Check if AccessKind list is enabled again Assert.Equal(True, viewModel.IsAccessListEnabled) End Function <WorkItem(858815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858815")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeAllowClassTypeKindForAttribute_CSharp() As Task Dim documentContentMarkup = <Text><![CDATA[ [Goo$$] class Program { static void Main(string[] args) { } }]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Attribute, isAttribute:=True) ' Check if only class is present Assert.Equal(1, viewModel.KindList.Count) Assert.Equal("class", viewModel.KindList(0)) Assert.Equal("GooAttribute", viewModel.TypeName) End Function <WorkItem(858815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858815")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeAllowClassTypeKindForAttribute_VisualBasic() As Task Dim documentContentMarkup = <Text><![CDATA[ <Blah$$> Class C End Class]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Attribute, isAttribute:=True) ' Check if only class is present Assert.Equal(1, viewModel.KindList.Count) Assert.Equal("Class", viewModel.KindList(0)) Assert.Equal("BlahAttribute", viewModel.TypeName) End Function <WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeWithCapsAttribute_VisualBasic() As Task Dim documentContentMarkup = <Text><![CDATA[ <GooAttribute$$> Public class CCC End class]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True) Assert.Equal("GooAttribute", viewModel.TypeName) End Function <WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeWithoutCapsAttribute_VisualBasic() As Task Dim documentContentMarkup = <Text><![CDATA[ <Gooattribute$$> Public class CCC End class]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True) Assert.Equal("GooattributeAttribute", viewModel.TypeName) End Function <WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeWithCapsAttribute_CSharp() As Task Dim documentContentMarkup = <Text><![CDATA[ [GooAttribute$$] public class CCC { }]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True) Assert.Equal("GooAttribute", viewModel.TypeName) End Function <WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeWithoutCapsAttribute_CSharp() As Task Dim documentContentMarkup = <Text><![CDATA[ [Gooattribute$$] public class CCC { }]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True) Assert.Equal("GooattributeAttribute", viewModel.TypeName) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeCheckOnlyPublic_CSharp_1() As Task Dim documentContentMarkup = <Text><![CDATA[ public class C : $$D { }]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.BaseList) ' Check if interface, class is present Assert.Equal(2, viewModel.KindList.Count) Assert.Equal("class", viewModel.KindList(0)) Assert.Equal("interface", viewModel.KindList(1)) ' Check if all Accessibility are present Assert.Equal(3, viewModel.AccessList.Count) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeCheckOnlyPublic_CSharp_2() As Task Dim documentContentMarkup = <Text><![CDATA[ public interface CCC : $$DDD { }]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=True) ' Check if interface, class is present Assert.Equal(1, viewModel.KindList.Count) Assert.Equal("interface", viewModel.KindList(0)) Assert.Equal(1, viewModel.AccessList.Count) Assert.Equal("public", viewModel.AccessList(0)) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeCheckOnlyPublic_VisualBasic_1() As Task Dim documentContentMarkup = <Text><![CDATA[ Public Class C Implements $$D End Class]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=False) ' Check if only Interface is present Assert.Equal(1, viewModel.KindList.Count) Assert.Equal("Interface", viewModel.KindList(0)) Assert.Equal(3, viewModel.AccessList.Count) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeCheckOnlyPublic_VisualBasic_2() As Task Dim documentContentMarkup = <Text><![CDATA[ Public Class CC Inherits $$DD End Class]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=True) ' Check if only class is present Assert.Equal(1, viewModel.KindList.Count) Assert.Equal("Class", viewModel.KindList(0)) ' Check if only Public is present Assert.Equal(1, viewModel.AccessList.Count) Assert.Equal("Public", viewModel.AccessList(0)) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeCheckOnlyPublic_VisualBasic_3() As Task Dim documentContentMarkup = <Text><![CDATA[ Public Interface CCC Inherits $$DDD End Interface]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=True) ' Check if only class is present Assert.Equal(1, viewModel.KindList.Count) Assert.Equal("Interface", viewModel.KindList(0)) ' Check if only Public is present Assert.Equal(1, viewModel.AccessList.Count) Assert.Equal("Public", viewModel.AccessList(0)) End Function <WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeWithModuleOption() As Task Dim workspaceXml = <Workspace> <Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true"> <Document FilePath="Test1.vb"> Module Program Sub Main(args As String()) Dim s as A.$$B.C End Sub End Module Namespace A End Namespace </Document> </Project> <Project Language="C#" AssemblyName="CS1" CommonReferences="true"/> </Workspace> Dim viewModel = Await GetViewModelAsync(workspaceXml, "", typeKindvalue:=TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module) ' Check if Module is present in addition to the normal options Assert.Equal(3, viewModel.KindList.Count) ' Select the project CS2 which has no documents. Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project viewModel.SelectedProject = projectToSelect ' C# does not have Module Assert.Equal(2, viewModel.KindList.Count) ' Switch back to the initial document projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project viewModel.SelectedProject = projectToSelect Assert.Equal(3, viewModel.KindList.Count) End Function <WorkItem(858826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858826")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeFileExtensionUpdate() As Task Dim workspaceXml = <Workspace> <Project Language="C#" AssemblyName="CS1" CommonReferences="true"> <Document FilePath="Test1.cs"> class Program { static void Main(string[] args) { Goo$$ bar; } } </Document> <Document FilePath="Test4.cs"></Document> </Project> <Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true"> <Document FilePath="Test2.vb"></Document> </Project> </Workspace> Dim viewModel = Await GetViewModelAsync(workspaceXml, "") ' Assert the current display Assert.Equal(viewModel.FileName, "Goo.cs") ' Select the project CS2 which has no documents. Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project viewModel.SelectedProject = projectToSelect ' Assert the new current display Assert.Equal(viewModel.FileName, "Goo.vb") ' Switch back to the initial document projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project viewModel.SelectedProject = projectToSelect ' Assert the display is back to the way it was before Assert.Equal(viewModel.FileName, "Goo.cs") ' Set the name with vb extension viewModel.FileName = "Goo.vb" ' On focus change,we trigger this method viewModel.UpdateFileNameExtension() ' Assert that the filename changes accordingly Assert.Equal(viewModel.FileName, "Goo.cs") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeExcludeGeneratedDocumentsFromList() As Task Dim workspaceXml = <Workspace> <Project Language="C#" AssemblyName="CS1" CommonReferences="true"> <Document FilePath="Test1.cs">$$</Document> <Document FilePath="Test2.cs"></Document> <Document FilePath="TemporaryGeneratedFile_test.cs"></Document> <Document FilePath="AssemblyInfo.cs"></Document> <Document FilePath="Test3.cs"></Document> </Project> </Workspace> Dim viewModel = Await GetViewModelAsync(workspaceXml, LanguageNames.CSharp) Dim expectedDocuments = {"Test1.cs", "Test2.cs", "AssemblyInfo.cs", "Test3.cs"} Assert.Equal(expectedDocuments, viewModel.DocumentList.Select(Function(d) d.Document.Name).ToArray()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeIntoGeneratedDocument() As Task Dim workspaceXml = <Workspace> <Project Language="C#" AssemblyName="CS1" CommonReferences="true"> <Document FilePath="Test.generated.cs"> class Program { static void Main(string[] args) { Goo$$ bar; } } </Document> <Document FilePath="Test2.cs"></Document> </Project> </Workspace> Dim viewModel = Await GetViewModelAsync(workspaceXml, LanguageNames.CSharp) ' Test the default values Assert.Equal(0, viewModel.AccessSelectIndex) Assert.Equal(0, viewModel.KindSelectIndex) Assert.Equal("Goo", viewModel.TypeName) Assert.Equal("Goo.cs", viewModel.FileName) Assert.Equal("Test.generated.cs", viewModel.SelectedDocument.Name) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeNewFileNameOptions() As Task Dim workspaceXml = <Workspace> <Project Language="C#" AssemblyName="CS1" CommonReferences="true" FilePath="C:\A\B\CS1.csproj"> <Document FilePath="C:\A\B\CDE\F\Test1.cs"> class Program { static void Main(string[] args) { Goo$$ bar; } } </Document> <Document FilePath="Test4.cs"></Document> <Document FilePath="C:\A\B\ExistingFile.cs"></Document> </Project> <Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true"> <Document FilePath="Test2.vb"></Document> </Project> </Workspace> Dim projectFolder = PopulateProjectFolders(New List(Of String)(), "\outer\", "\outer\inner\") Dim viewModel = Await GetViewModelAsync(workspaceXml, "", projectFolders:=projectFolder) viewModel.IsNewFile = True ' Assert the current display Assert.Equal(viewModel.FileName, "Goo.cs") ' Set the folder to \outer\ viewModel.FileName = viewModel.ProjectFolders(0) Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) ' Set the Filename to \\something.cs viewModel.FileName = "\\ExistingFile.cs" viewModel.UpdateFileNameExtension() Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) ' Set the Filename to an existing file viewModel.FileName = "..\..\ExistingFile.cs" viewModel.UpdateFileNameExtension() Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) ' Set the Filename to empty viewModel.FileName = " " viewModel.UpdateFileNameExtension() Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) ' Set the Filename with more than permissible characters viewModel.FileName = "sjkygjksdfygujysdkgkufsdfrgujdfyhgjksuydfujkgysdjkfuygjkusydfjusyfkjsdfygjusydfgjkuysdkfjugyksdfjkusydfgjkusdfyjgukysdjfyjkusydfgjuysdfgjuysdfjgsdjfugjusdfygjuysdfjugyjdufgsgdfvsgdvgtsdvfgsvdfgsdgfgdsvfgsdvfgsvdfgsdfsjkygjksdfygujysdkgkufsdfrgujdfyhgjksuydfujkgysdjkfuygjkusydfjusyfkjsdfygjusydfgjkuysdkfjugyksdfjkusydfgjkusdfyjgukysdjfyjkusydfgjuysdfgjuysdfjgsdjfugjusdfygjuysdfjugyjdufgsgdfvsgdvgtsdvfgsvdfgsdgfgdsvfgsdvfgsvdfgsdf.cs" Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) ' Set the Filename with keywords viewModel.FileName = "com1\goo.cs" Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) ' Set the Filename with ".." viewModel.FileName = "..\..\goo.cs" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) ' Set the Filename with ".." viewModel.FileName = "..\.\..\.\goo.cs" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) End Function <WorkItem(898452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/898452")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeIntoNewFileWithInvalidIdentifierFolderName() As Task Dim documentContentMarkupCSharp = <Text><![CDATA[ class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkupCSharp, "C#", projectRootFilePath:="C:\OuterFolder\InnerFolder\") viewModel.IsNewFile = True Dim foldersAreInvalid = "Folders are not valid identifiers" viewModel.FileName = "123\456\Wow.cs" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid) viewModel.FileName = "@@@@\######\Woow.cs" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid) viewModel.FileName = "....a\.....b\Wow.cs" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid) Dim documentContentMarkupVB = <Text><![CDATA[ class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } }"]]></Text> viewModel = Await GetViewModelAsync(documentContentMarkupVB, "Visual Basic", projectRootFilePath:="C:\OuterFolder1\InnerFolder1\") viewModel.IsNewFile = True viewModel.FileName = "123\456\Wow.vb" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid) viewModel.FileName = "@@@@\######\Woow.vb" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid) viewModel.FileName = "....a\.....b\Wow.vb" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid) End Function <WorkItem(898563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/898563")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateType_DontGenerateIntoExistingFile() As Task ' Get a Temp Folder Path Dim projectRootFolder = Path.GetTempPath() ' Get a random filename Dim randomFileName = Path.GetRandomFileName() ' Get the final combined path of the file Dim pathString = Path.Combine(projectRootFolder, randomFileName) ' Create the file Dim fs = File.Create(pathString) Dim bytearray = New Byte() {0, 1} fs.Write(bytearray, 0, bytearray.Length) fs.Close() Dim documentContentMarkupCSharp = <Text><![CDATA[ class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkupCSharp, "C#", projectRootFilePath:=projectRootFolder) viewModel.IsNewFile = True viewModel.FileName = randomFileName Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) ' Cleanup File.Delete(pathString) End Function Private Shared Function PopulateProjectFolders(list As List(Of String), ParamArray values As String()) As List(Of String) list.AddRange(values) Return list End Function Private Shared Function GetOneProjectWorkspace( documentContent As XElement, languageName As String, projectName As String, documentName As String, projectRootFilePath As String) As XElement Dim documentNameWithExtension = documentName + If(languageName = "C#", ".cs", ".vb") If projectRootFilePath Is Nothing Then Return <Workspace> <Project Language=<%= languageName %> AssemblyName=<%= projectName %> CommonReferences="true"> <Document FilePath=<%= documentNameWithExtension %>><%= documentContent.NormalizedValue.Replace(vbCrLf, vbLf) %></Document> </Project> </Workspace> Else Dim projectFilePath As String = projectRootFilePath + projectName + If(languageName = "C#", ".csproj", ".vbproj") Dim documentFilePath As String = projectRootFilePath + documentNameWithExtension Return <Workspace> <Project Language=<%= languageName %> AssemblyName=<%= projectName %> CommonReferences="true" FilePath=<%= projectFilePath %>> <Document FilePath=<%= documentFilePath %>><%= documentContent.NormalizedValue.Replace(vbCrLf, vbLf) %></Document> </Project> </Workspace> End If End Function Private Shared Async Function GetViewModelAsync( content As XElement, languageName As String, Optional isNewFile As Boolean = False, Optional accessSelectString As String = "", Optional kindSelectString As String = "", Optional projectName As String = "Assembly1", Optional documentName As String = "Test1", Optional typeKindvalue As TypeKindOptions = TypeKindOptions.AllOptions, Optional isPublicOnlyAccessibility As Boolean = False, Optional isAttribute As Boolean = False, Optional projectFolders As List(Of String) = Nothing, Optional projectRootFilePath As String = Nothing) As Tasks.Task(Of GenerateTypeDialogViewModel) Dim workspaceXml = If(content.Name.LocalName = "Workspace", content, GetOneProjectWorkspace(content, languageName, projectName, documentName, projectRootFilePath)) Using workspace = TestWorkspace.Create(workspaceXml) Dim testDoc = workspace.Documents.SingleOrDefault(Function(d) d.CursorPosition.HasValue) Assert.NotNull(testDoc) Dim document = workspace.CurrentSolution.GetDocument(testDoc.Id) Dim tree = Await document.GetSyntaxTreeAsync() Dim token = Await tree.GetTouchingWordAsync(testDoc.CursorPosition.Value, document.GetLanguageService(Of ISyntaxFactsService)(), CancellationToken.None) Dim typeName = token.ToString() Dim testProjectManagementService As IProjectManagementService = Nothing If projectFolders IsNot Nothing Then testProjectManagementService = New TestProjectManagementService(projectFolders) End If Dim syntaxFactsService = document.GetLanguageService(Of ISyntaxFactsService)() Return New GenerateTypeDialogViewModel( document, New TestNotificationService(), testProjectManagementService, syntaxFactsService, New GenerateTypeDialogOptions(isPublicOnlyAccessibility, typeKindvalue, isAttribute), typeName, If(document.Project.Language = LanguageNames.CSharp, ".cs", ".vb"), isNewFile, accessSelectString, kindSelectString) End Using End Function End Class Friend Class TestProjectManagementService Implements IProjectManagementService Private ReadOnly _projectFolders As List(Of String) Public Sub New(projectFolders As List(Of String)) Me._projectFolders = projectFolders End Sub Public Function GetDefaultNamespace(project As Project, workspace As Microsoft.CodeAnalysis.Workspace) As String Implements IProjectManagementService.GetDefaultNamespace Return "" End Function Public Function GetFolders(projectId As ProjectId, workspace As Microsoft.CodeAnalysis.Workspace) As IList(Of String) Implements IProjectManagementService.GetFolders Return Me._projectFolders 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.IO Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.GenerateType Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.ProjectManagement Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.GenerateType <[UseExportProvider]> Public Class GenerateTypeViewModelTests Private Shared ReadOnly s_assembly1_Name As String = "Assembly1" Private Shared ReadOnly s_test1_Name As String = "Test1" Private Shared ReadOnly s_submit_failed_unexpectedly As String = "Submit failed unexpectedly." Private Shared ReadOnly s_submit_passed_unexpectedly As String = "Submit passed unexpectedly. Submit should fail here" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeExistingFileCSharp() As Task Dim documentContentMarkup = <Text><![CDATA[ class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, "C#") ' Test the default values Assert.Equal(0, viewModel.AccessSelectIndex) Assert.Equal(0, viewModel.KindSelectIndex) Assert.Equal("Goo", viewModel.TypeName) Assert.Equal("Goo.cs", viewModel.FileName) Assert.Equal(s_assembly1_Name, viewModel.SelectedProject.Name) Assert.Equal(s_test1_Name + ".cs", viewModel.SelectedDocument.Name) Assert.Equal(True, viewModel.IsExistingFile) ' Set the Radio to new file viewModel.IsNewFile = True Assert.Equal(True, viewModel.IsNewFile) Assert.Equal(False, viewModel.IsExistingFile) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeExistingFileVisualBasic() As Task Dim documentContentMarkup = <Text><![CDATA[ Module Program Sub Main(args As String()) Dim x As A.B.Goo$$ = Nothing End Sub End Module Namespace A Namespace B End Namespace End Namespace"]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, "Visual Basic") ' Test the default values Assert.Equal(0, viewModel.AccessSelectIndex) Assert.Equal(0, viewModel.KindSelectIndex) Assert.Equal("Goo", viewModel.TypeName) Assert.Equal("Goo.vb", viewModel.FileName) Assert.Equal(s_assembly1_Name, viewModel.SelectedProject.Name) Assert.Equal(s_test1_Name + ".vb", viewModel.SelectedDocument.Name) Assert.Equal(True, viewModel.IsExistingFile) ' Set the Radio to new file viewModel.IsNewFile = True Assert.Equal(True, viewModel.IsNewFile) Assert.Equal(False, viewModel.IsExistingFile) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeNewFileBothLanguage() As Task Dim documentContentMarkup = <Text><![CDATA[ class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, "C#", projectRootFilePath:="C:\OuterFolder\InnerFolder\") viewModel.IsNewFile = True ' Feed a filename and check if the change is effective viewModel.FileName = "Wow" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.Equal("Wow.cs", viewModel.FileName) viewModel.FileName = "Goo\Bar\Woow" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.Equal("Woow.cs", viewModel.FileName) Assert.Equal(2, viewModel.Folders.Count) Assert.Equal("Goo", viewModel.Folders(0)) Assert.Equal("Bar", viewModel.Folders(1)) viewModel.FileName = "\ name has space \ Goo \Bar\ Woow" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.Equal("Woow.cs", viewModel.FileName) Assert.Equal(3, viewModel.Folders.Count) Assert.Equal("name has space", viewModel.Folders(0)) Assert.Equal("Goo", viewModel.Folders(1)) Assert.Equal("Bar", viewModel.Folders(2)) ' Set it to invalid identifier viewModel.FileName = "w?d" viewModel.UpdateFileNameExtension() Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) viewModel.FileName = "wow\w?d" viewModel.UpdateFileNameExtension() Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) viewModel.FileName = "w?d\wdd" viewModel.UpdateFileNameExtension() Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeProjectChangeAndDependencyBothLanguage() As Task Dim workspaceXml = <Workspace> <Project Language="C#" AssemblyName="CS1" CommonReferences="true"> <Document FilePath="Test1.cs"> class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } } </Document> <Document FilePath="Test4.cs"></Document> </Project> <Project Language="C#" AssemblyName="CS2" CommonReferences="true"> <ProjectReference>CS1</ProjectReference> </Project> <Project Language="C#" AssemblyName="CS3" CommonReferences="true"> <ProjectReference>CS2</ProjectReference> </Project> <Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true"> <Document FilePath="Test2.vb"></Document> <Document FilePath="Test3.vb"></Document> </Project> </Workspace> Dim viewModel = Await GetViewModelAsync(workspaceXml, "") ' Only 2 Projects can be selected because CS2 and CS3 will introduce cyclic dependency Assert.Equal(2, viewModel.ProjectList.Count) Assert.Equal(2, viewModel.DocumentList.Count()) viewModel.DocumentSelectIndex = 1 Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project Dim monitor = New PropertyChangedTestMonitor(viewModel) ' Check to see if the values are reset when there is a change in the project selection viewModel.SelectedProject = projectToSelect Assert.Equal(2, viewModel.DocumentList.Count()) Assert.Equal(0, viewModel.DocumentSelectIndex) Assert.Equal(1, viewModel.ProjectSelectIndex) monitor.VerifyExpectations() monitor.Detach() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeDisableExistingFileForEmptyProject() As Task Dim workspaceXml = <Workspace> <Project Language="C#" AssemblyName="CS1" CommonReferences="true"> <Document FilePath="Test1.cs"> class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } } </Document> <Document FilePath="Test4.cs"></Document> </Project> <Project Language="C#" AssemblyName="CS2" CommonReferences="true"/> </Workspace> Dim viewModel = Await GetViewModelAsync(workspaceXml, "") ' Select the project CS2 which has no documents. Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS2").Single().Project viewModel.SelectedProject = projectToSelect ' Check if the option for Existing File is disabled Assert.Equal(0, viewModel.DocumentList.Count()) Assert.Equal(False, viewModel.IsExistingFileEnabled) ' Select the project CS1 which has documents projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project viewModel.SelectedProject = projectToSelect ' Check if the option for Existing File is enabled Assert.Equal(2, viewModel.DocumentList.Count()) Assert.Equal(True, viewModel.IsExistingFileEnabled) End Function <WorkItem(858815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858815")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeAllowPublicAccessOnlyForGenerationIntoOtherProject() As Task Dim workspaceXml = <Workspace> <Project Language="C#" AssemblyName="CS1" CommonReferences="true"> <Document FilePath="Test1.cs"> class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } } </Document> <Document FilePath="Test4.cs"></Document> </Project> <Project Language="C#" AssemblyName="CS2" CommonReferences="true"/> </Workspace> Dim viewModel = Await GetViewModelAsync(workspaceXml, "") viewModel.SelectedAccessibilityString = "Default" ' Check if the AccessKind List is enabled Assert.Equal(True, viewModel.IsAccessListEnabled) ' Select the project CS2 which has no documents. Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS2").Single().Project viewModel.SelectedProject = projectToSelect ' Check if access kind is set to Public and the AccessKind is set to be disabled Assert.Equal(2, viewModel.AccessSelectIndex) Assert.Equal(False, viewModel.IsAccessListEnabled) ' Switch back to the initial document projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project viewModel.SelectedProject = projectToSelect ' Check if AccessKind list is enabled again Assert.Equal(True, viewModel.IsAccessListEnabled) End Function <WorkItem(858815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858815")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeAllowClassTypeKindForAttribute_CSharp() As Task Dim documentContentMarkup = <Text><![CDATA[ [Goo$$] class Program { static void Main(string[] args) { } }]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Attribute, isAttribute:=True) ' Check if only class is present Assert.Equal(1, viewModel.KindList.Count) Assert.Equal("class", viewModel.KindList(0)) Assert.Equal("GooAttribute", viewModel.TypeName) End Function <WorkItem(858815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858815")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeAllowClassTypeKindForAttribute_VisualBasic() As Task Dim documentContentMarkup = <Text><![CDATA[ <Blah$$> Class C End Class]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Attribute, isAttribute:=True) ' Check if only class is present Assert.Equal(1, viewModel.KindList.Count) Assert.Equal("Class", viewModel.KindList(0)) Assert.Equal("BlahAttribute", viewModel.TypeName) End Function <WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeWithCapsAttribute_VisualBasic() As Task Dim documentContentMarkup = <Text><![CDATA[ <GooAttribute$$> Public class CCC End class]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True) Assert.Equal("GooAttribute", viewModel.TypeName) End Function <WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeWithoutCapsAttribute_VisualBasic() As Task Dim documentContentMarkup = <Text><![CDATA[ <Gooattribute$$> Public class CCC End class]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True) Assert.Equal("GooattributeAttribute", viewModel.TypeName) End Function <WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeWithCapsAttribute_CSharp() As Task Dim documentContentMarkup = <Text><![CDATA[ [GooAttribute$$] public class CCC { }]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True) Assert.Equal("GooAttribute", viewModel.TypeName) End Function <WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeWithoutCapsAttribute_CSharp() As Task Dim documentContentMarkup = <Text><![CDATA[ [Gooattribute$$] public class CCC { }]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True) Assert.Equal("GooattributeAttribute", viewModel.TypeName) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeCheckOnlyPublic_CSharp_1() As Task Dim documentContentMarkup = <Text><![CDATA[ public class C : $$D { }]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.BaseList) ' Check if interface, class is present Assert.Equal(2, viewModel.KindList.Count) Assert.Equal("class", viewModel.KindList(0)) Assert.Equal("interface", viewModel.KindList(1)) ' Check if all Accessibility are present Assert.Equal(3, viewModel.AccessList.Count) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeCheckOnlyPublic_CSharp_2() As Task Dim documentContentMarkup = <Text><![CDATA[ public interface CCC : $$DDD { }]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=True) ' Check if interface, class is present Assert.Equal(1, viewModel.KindList.Count) Assert.Equal("interface", viewModel.KindList(0)) Assert.Equal(1, viewModel.AccessList.Count) Assert.Equal("public", viewModel.AccessList(0)) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeCheckOnlyPublic_VisualBasic_1() As Task Dim documentContentMarkup = <Text><![CDATA[ Public Class C Implements $$D End Class]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=False) ' Check if only Interface is present Assert.Equal(1, viewModel.KindList.Count) Assert.Equal("Interface", viewModel.KindList(0)) Assert.Equal(3, viewModel.AccessList.Count) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeCheckOnlyPublic_VisualBasic_2() As Task Dim documentContentMarkup = <Text><![CDATA[ Public Class CC Inherits $$DD End Class]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=True) ' Check if only class is present Assert.Equal(1, viewModel.KindList.Count) Assert.Equal("Class", viewModel.KindList(0)) ' Check if only Public is present Assert.Equal(1, viewModel.AccessList.Count) Assert.Equal("Public", viewModel.AccessList(0)) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeCheckOnlyPublic_VisualBasic_3() As Task Dim documentContentMarkup = <Text><![CDATA[ Public Interface CCC Inherits $$DDD End Interface]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=True) ' Check if only class is present Assert.Equal(1, viewModel.KindList.Count) Assert.Equal("Interface", viewModel.KindList(0)) ' Check if only Public is present Assert.Equal(1, viewModel.AccessList.Count) Assert.Equal("Public", viewModel.AccessList(0)) End Function <WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeWithModuleOption() As Task Dim workspaceXml = <Workspace> <Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true"> <Document FilePath="Test1.vb"> Module Program Sub Main(args As String()) Dim s as A.$$B.C End Sub End Module Namespace A End Namespace </Document> </Project> <Project Language="C#" AssemblyName="CS1" CommonReferences="true"/> </Workspace> Dim viewModel = Await GetViewModelAsync(workspaceXml, "", typeKindvalue:=TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module) ' Check if Module is present in addition to the normal options Assert.Equal(3, viewModel.KindList.Count) ' Select the project CS2 which has no documents. Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project viewModel.SelectedProject = projectToSelect ' C# does not have Module Assert.Equal(2, viewModel.KindList.Count) ' Switch back to the initial document projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project viewModel.SelectedProject = projectToSelect Assert.Equal(3, viewModel.KindList.Count) End Function <WorkItem(858826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858826")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeFileExtensionUpdate() As Task Dim workspaceXml = <Workspace> <Project Language="C#" AssemblyName="CS1" CommonReferences="true"> <Document FilePath="Test1.cs"> class Program { static void Main(string[] args) { Goo$$ bar; } } </Document> <Document FilePath="Test4.cs"></Document> </Project> <Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true"> <Document FilePath="Test2.vb"></Document> </Project> </Workspace> Dim viewModel = Await GetViewModelAsync(workspaceXml, "") ' Assert the current display Assert.Equal(viewModel.FileName, "Goo.cs") ' Select the project CS2 which has no documents. Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project viewModel.SelectedProject = projectToSelect ' Assert the new current display Assert.Equal(viewModel.FileName, "Goo.vb") ' Switch back to the initial document projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project viewModel.SelectedProject = projectToSelect ' Assert the display is back to the way it was before Assert.Equal(viewModel.FileName, "Goo.cs") ' Set the name with vb extension viewModel.FileName = "Goo.vb" ' On focus change,we trigger this method viewModel.UpdateFileNameExtension() ' Assert that the filename changes accordingly Assert.Equal(viewModel.FileName, "Goo.cs") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeExcludeGeneratedDocumentsFromList() As Task Dim workspaceXml = <Workspace> <Project Language="C#" AssemblyName="CS1" CommonReferences="true"> <Document FilePath="Test1.cs">$$</Document> <Document FilePath="Test2.cs"></Document> <Document FilePath="TemporaryGeneratedFile_test.cs"></Document> <Document FilePath="AssemblyInfo.cs"></Document> <Document FilePath="Test3.cs"></Document> </Project> </Workspace> Dim viewModel = Await GetViewModelAsync(workspaceXml, LanguageNames.CSharp) Dim expectedDocuments = {"Test1.cs", "Test2.cs", "AssemblyInfo.cs", "Test3.cs"} Assert.Equal(expectedDocuments, viewModel.DocumentList.Select(Function(d) d.Document.Name).ToArray()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeIntoGeneratedDocument() As Task Dim workspaceXml = <Workspace> <Project Language="C#" AssemblyName="CS1" CommonReferences="true"> <Document FilePath="Test.generated.cs"> class Program { static void Main(string[] args) { Goo$$ bar; } } </Document> <Document FilePath="Test2.cs"></Document> </Project> </Workspace> Dim viewModel = Await GetViewModelAsync(workspaceXml, LanguageNames.CSharp) ' Test the default values Assert.Equal(0, viewModel.AccessSelectIndex) Assert.Equal(0, viewModel.KindSelectIndex) Assert.Equal("Goo", viewModel.TypeName) Assert.Equal("Goo.cs", viewModel.FileName) Assert.Equal("Test.generated.cs", viewModel.SelectedDocument.Name) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeNewFileNameOptions() As Task Dim workspaceXml = <Workspace> <Project Language="C#" AssemblyName="CS1" CommonReferences="true" FilePath="C:\A\B\CS1.csproj"> <Document FilePath="C:\A\B\CDE\F\Test1.cs"> class Program { static void Main(string[] args) { Goo$$ bar; } } </Document> <Document FilePath="Test4.cs"></Document> <Document FilePath="C:\A\B\ExistingFile.cs"></Document> </Project> <Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true"> <Document FilePath="Test2.vb"></Document> </Project> </Workspace> Dim projectFolder = PopulateProjectFolders(New List(Of String)(), "\outer\", "\outer\inner\") Dim viewModel = Await GetViewModelAsync(workspaceXml, "", projectFolders:=projectFolder) viewModel.IsNewFile = True ' Assert the current display Assert.Equal(viewModel.FileName, "Goo.cs") ' Set the folder to \outer\ viewModel.FileName = viewModel.ProjectFolders(0) Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) ' Set the Filename to \\something.cs viewModel.FileName = "\\ExistingFile.cs" viewModel.UpdateFileNameExtension() Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) ' Set the Filename to an existing file viewModel.FileName = "..\..\ExistingFile.cs" viewModel.UpdateFileNameExtension() Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) ' Set the Filename to empty viewModel.FileName = " " viewModel.UpdateFileNameExtension() Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) ' Set the Filename with more than permissible characters viewModel.FileName = "sjkygjksdfygujysdkgkufsdfrgujdfyhgjksuydfujkgysdjkfuygjkusydfjusyfkjsdfygjusydfgjkuysdkfjugyksdfjkusydfgjkusdfyjgukysdjfyjkusydfgjuysdfgjuysdfjgsdjfugjusdfygjuysdfjugyjdufgsgdfvsgdvgtsdvfgsvdfgsdgfgdsvfgsdvfgsvdfgsdfsjkygjksdfygujysdkgkufsdfrgujdfyhgjksuydfujkgysdjkfuygjkusydfjusyfkjsdfygjusydfgjkuysdkfjugyksdfjkusydfgjkusdfyjgukysdjfyjkusydfgjuysdfgjuysdfjgsdjfugjusdfygjuysdfjugyjdufgsgdfvsgdvgtsdvfgsvdfgsdgfgdsvfgsdvfgsvdfgsdf.cs" Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) ' Set the Filename with keywords viewModel.FileName = "com1\goo.cs" Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) ' Set the Filename with ".." viewModel.FileName = "..\..\goo.cs" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) ' Set the Filename with ".." viewModel.FileName = "..\.\..\.\goo.cs" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) End Function <WorkItem(898452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/898452")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateTypeIntoNewFileWithInvalidIdentifierFolderName() As Task Dim documentContentMarkupCSharp = <Text><![CDATA[ class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkupCSharp, "C#", projectRootFilePath:="C:\OuterFolder\InnerFolder\") viewModel.IsNewFile = True Dim foldersAreInvalid = "Folders are not valid identifiers" viewModel.FileName = "123\456\Wow.cs" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid) viewModel.FileName = "@@@@\######\Woow.cs" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid) viewModel.FileName = "....a\.....b\Wow.cs" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid) Dim documentContentMarkupVB = <Text><![CDATA[ class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } }"]]></Text> viewModel = Await GetViewModelAsync(documentContentMarkupVB, "Visual Basic", projectRootFilePath:="C:\OuterFolder1\InnerFolder1\") viewModel.IsNewFile = True viewModel.FileName = "123\456\Wow.vb" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid) viewModel.FileName = "@@@@\######\Woow.vb" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid) viewModel.FileName = "....a\.....b\Wow.vb" viewModel.UpdateFileNameExtension() Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly) Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid) End Function <WorkItem(898563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/898563")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function TestGenerateType_DontGenerateIntoExistingFile() As Task ' Get a Temp Folder Path Dim projectRootFolder = Path.GetTempPath() ' Get a random filename Dim randomFileName = Path.GetRandomFileName() ' Get the final combined path of the file Dim pathString = Path.Combine(projectRootFolder, randomFileName) ' Create the file Dim fs = File.Create(pathString) Dim bytearray = New Byte() {0, 1} fs.Write(bytearray, 0, bytearray.Length) fs.Close() Dim documentContentMarkupCSharp = <Text><![CDATA[ class Program { static void Main(string[] args) { A.B.Goo$$ bar; } } namespace A { namespace B { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(documentContentMarkupCSharp, "C#", projectRootFilePath:=projectRootFolder) viewModel.IsNewFile = True viewModel.FileName = randomFileName Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly) ' Cleanup File.Delete(pathString) End Function Private Shared Function PopulateProjectFolders(list As List(Of String), ParamArray values As String()) As List(Of String) list.AddRange(values) Return list End Function Private Shared Function GetOneProjectWorkspace( documentContent As XElement, languageName As String, projectName As String, documentName As String, projectRootFilePath As String) As XElement Dim documentNameWithExtension = documentName + If(languageName = "C#", ".cs", ".vb") If projectRootFilePath Is Nothing Then Return <Workspace> <Project Language=<%= languageName %> AssemblyName=<%= projectName %> CommonReferences="true"> <Document FilePath=<%= documentNameWithExtension %>><%= documentContent.NormalizedValue.Replace(vbCrLf, vbLf) %></Document> </Project> </Workspace> Else Dim projectFilePath As String = projectRootFilePath + projectName + If(languageName = "C#", ".csproj", ".vbproj") Dim documentFilePath As String = projectRootFilePath + documentNameWithExtension Return <Workspace> <Project Language=<%= languageName %> AssemblyName=<%= projectName %> CommonReferences="true" FilePath=<%= projectFilePath %>> <Document FilePath=<%= documentFilePath %>><%= documentContent.NormalizedValue.Replace(vbCrLf, vbLf) %></Document> </Project> </Workspace> End If End Function Private Shared Async Function GetViewModelAsync( content As XElement, languageName As String, Optional isNewFile As Boolean = False, Optional accessSelectString As String = "", Optional kindSelectString As String = "", Optional projectName As String = "Assembly1", Optional documentName As String = "Test1", Optional typeKindvalue As TypeKindOptions = TypeKindOptions.AllOptions, Optional isPublicOnlyAccessibility As Boolean = False, Optional isAttribute As Boolean = False, Optional projectFolders As List(Of String) = Nothing, Optional projectRootFilePath As String = Nothing) As Tasks.Task(Of GenerateTypeDialogViewModel) Dim workspaceXml = If(content.Name.LocalName = "Workspace", content, GetOneProjectWorkspace(content, languageName, projectName, documentName, projectRootFilePath)) Using workspace = TestWorkspace.Create(workspaceXml) Dim testDoc = workspace.Documents.SingleOrDefault(Function(d) d.CursorPosition.HasValue) Assert.NotNull(testDoc) Dim document = workspace.CurrentSolution.GetDocument(testDoc.Id) Dim tree = Await document.GetSyntaxTreeAsync() Dim token = Await tree.GetTouchingWordAsync(testDoc.CursorPosition.Value, document.GetLanguageService(Of ISyntaxFactsService)(), CancellationToken.None) Dim typeName = token.ToString() Dim testProjectManagementService As IProjectManagementService = Nothing If projectFolders IsNot Nothing Then testProjectManagementService = New TestProjectManagementService(projectFolders) End If Dim syntaxFactsService = document.GetLanguageService(Of ISyntaxFactsService)() Return New GenerateTypeDialogViewModel( document, New TestNotificationService(), testProjectManagementService, syntaxFactsService, New GenerateTypeDialogOptions(isPublicOnlyAccessibility, typeKindvalue, isAttribute), typeName, If(document.Project.Language = LanguageNames.CSharp, ".cs", ".vb"), isNewFile, accessSelectString, kindSelectString) End Using End Function End Class Friend Class TestProjectManagementService Implements IProjectManagementService Private ReadOnly _projectFolders As List(Of String) Public Sub New(projectFolders As List(Of String)) Me._projectFolders = projectFolders End Sub Public Function GetDefaultNamespace(project As Project, workspace As Microsoft.CodeAnalysis.Workspace) As String Implements IProjectManagementService.GetDefaultNamespace Return "" End Function Public Function GetFolders(projectId As ProjectId, workspace As Microsoft.CodeAnalysis.Workspace) As IList(Of String) Implements IProjectManagementService.GetFolders Return Me._projectFolders End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/TestUtilities/EditAndContinue/ActiveStatementTestHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.EditAndContinue.Contracts; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal static class ActiveStatementTestHelpers { public static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfosCSharp( string[] markedSources, string[]? filePaths = null, int[]? methodRowIds = null, Guid[]? modules = null, int[]? methodVersions = null, int[]? ilOffsets = null, ActiveStatementFlags[]? flags = null) { return ActiveStatementsDescription.GetActiveStatementDebugInfos( (source, path) => SyntaxFactory.ParseSyntaxTree(source, path: path), markedSources, filePaths, extension: ".cs", methodRowIds, modules, methodVersions, ilOffsets, flags); } public static string Delete(string src, string marker) { while (true) { var startStr = "/*delete" + marker; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length; src = src.Substring(0, start) + src.Substring(end); } } /// <summary> /// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/. /// </summary> public static string InsertNewLines(string src, string marker) { while (true) { var startStr = "/*insert" + marker + "["; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var startOfLineCount = start + startStr.Length; var endOfLineCount = src.IndexOf(']', startOfLineCount); var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount)); var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length; src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end); } } public static string Update(string src, string marker) => InsertNewLines(Delete(src, marker), marker); public static string InspectActiveStatement(ActiveStatement statement) => $"{statement.Ordinal}: {statement.FileSpan} flags=[{statement.Flags}]"; public static string InspectActiveStatementAndInstruction(ActiveStatement statement) => InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay(); public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text) => InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'"; public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update) => $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}"; public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions) => regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}"); public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r) => $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}"; public static string GetFirstLineText(LinePositionSpan span, SourceText text) => text.Lines[span.Start.Line].ToString().Trim(); public static string InspectSequencePointUpdates(SequencePointUpdates updates) => $"{updates.FileName}: [{string.Join(", ", updates.LineUpdates.Select(u => $"{u.OldLine} -> {u.NewLine}"))}]"; public static IEnumerable<string> Inspect(this IEnumerable<SequencePointUpdates> updates) => updates.Select(InspectSequencePointUpdates); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.EditAndContinue.Contracts; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal static class ActiveStatementTestHelpers { public static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfosCSharp( string[] markedSources, string[]? filePaths = null, int[]? methodRowIds = null, Guid[]? modules = null, int[]? methodVersions = null, int[]? ilOffsets = null, ActiveStatementFlags[]? flags = null) { return ActiveStatementsDescription.GetActiveStatementDebugInfos( (source, path) => SyntaxFactory.ParseSyntaxTree(source, path: path), markedSources, filePaths, extension: ".cs", methodRowIds, modules, methodVersions, ilOffsets, flags); } public static string Delete(string src, string marker) { while (true) { var startStr = "/*delete" + marker; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length; src = src.Substring(0, start) + src.Substring(end); } } /// <summary> /// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/. /// </summary> public static string InsertNewLines(string src, string marker) { while (true) { var startStr = "/*insert" + marker + "["; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var startOfLineCount = start + startStr.Length; var endOfLineCount = src.IndexOf(']', startOfLineCount); var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount)); var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length; src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end); } } public static string Update(string src, string marker) => InsertNewLines(Delete(src, marker), marker); public static string InspectActiveStatement(ActiveStatement statement) => $"{statement.Ordinal}: {statement.FileSpan} flags=[{statement.Flags}]"; public static string InspectActiveStatementAndInstruction(ActiveStatement statement) => InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay(); public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text) => InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'"; public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update) => $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}"; public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions) => regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}"); public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r) => $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}"; public static string GetFirstLineText(LinePositionSpan span, SourceText text) => text.Lines[span.Start.Line].ToString().Trim(); public static string InspectSequencePointUpdates(SequencePointUpdates updates) => $"{updates.FileName}: [{string.Join(", ", updates.LineUpdates.Select(u => $"{u.OldLine} -> {u.NewLine}"))}]"; public static IEnumerable<string> Inspect(this IEnumerable<SequencePointUpdates> updates) => updates.Select(InspectSequencePointUpdates); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/ProjectSystem/VisualStudioProjectCreationInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed class VisualStudioProjectCreationInfo { public string? AssemblyName { get; set; } public CompilationOptions? CompilationOptions { get; set; } public string? FilePath { get; set; } public ParseOptions? ParseOptions { get; set; } public IVsHierarchy? Hierarchy { get; set; } public Guid ProjectGuid { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed class VisualStudioProjectCreationInfo { public string? AssemblyName { get; set; } public CompilationOptions? CompilationOptions { get; set; } public string? FilePath { get; set; } public ParseOptions? ParseOptions { get; set; } public IVsHierarchy? Hierarchy { get; set; } public Guid ProjectGuid { get; set; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/Core.Wpf/Interactive/InteractiveCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using System.Threading; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Interactive { internal abstract class InteractiveCommandHandler : ICommandHandler<ExecuteInInteractiveCommandArgs>, ICommandHandler<CopyToInteractiveCommandArgs> { private readonly IContentTypeRegistryService _contentTypeRegistryService; private readonly EditorOptionsService _editorOptionsService; private readonly IEditorOperationsFactoryService _editorOperationsFactoryService; protected InteractiveCommandHandler( IContentTypeRegistryService contentTypeRegistryService, EditorOptionsService editorOptionsService, IEditorOperationsFactoryService editorOperationsFactoryService) { _contentTypeRegistryService = contentTypeRegistryService; _editorOptionsService = editorOptionsService; _editorOperationsFactoryService = editorOperationsFactoryService; } protected IContentTypeRegistryService ContentTypeRegistryService { get { return _contentTypeRegistryService; } } protected abstract IInteractiveWindow OpenInteractiveWindow(bool focus); protected abstract ISendToInteractiveSubmissionProvider SendToInteractiveSubmissionProvider { get; } public string DisplayName => EditorFeaturesResources.Interactive; private string GetSelectedText(EditorCommandArgs args, CancellationToken cancellationToken) { var editorOptions = _editorOptionsService.Factory.GetOptions(args.SubjectBuffer); return SendToInteractiveSubmissionProvider.GetSelectedText(editorOptions, args, cancellationToken); } CommandState ICommandHandler<ExecuteInInteractiveCommandArgs>.GetCommandState(ExecuteInInteractiveCommandArgs args) => CommandState.Available; bool ICommandHandler<ExecuteInInteractiveCommandArgs>.ExecuteCommand(ExecuteInInteractiveCommandArgs args, CommandExecutionContext context) { var window = OpenInteractiveWindow(focus: false); using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesWpfResources.Executing_selection_in_Interactive_Window)) { var submission = GetSelectedText(args, context.OperationContext.UserCancellationToken); if (!string.IsNullOrWhiteSpace(submission)) { window.SubmitAsync(new string[] { submission }); } } return true; } CommandState ICommandHandler<CopyToInteractiveCommandArgs>.GetCommandState(CopyToInteractiveCommandArgs args) => CommandState.Available; bool ICommandHandler<CopyToInteractiveCommandArgs>.ExecuteCommand(CopyToInteractiveCommandArgs args, CommandExecutionContext context) { var window = OpenInteractiveWindow(focus: true); var buffer = window.CurrentLanguageBuffer; if (buffer != null) { CopyToWindow(window, args, context); } else { Action action = null; action = new Action(() => { window.ReadyForInput -= action; CopyToWindow(window, args, context); }); window.ReadyForInput += action; } return true; } private void CopyToWindow(IInteractiveWindow window, CopyToInteractiveCommandArgs args, CommandExecutionContext context) { var buffer = window.CurrentLanguageBuffer; Debug.Assert(buffer != null); using (var edit = buffer.CreateEdit()) using (var waitScope = context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesWpfResources.Copying_selection_to_Interactive_Window)) { var text = GetSelectedText(args, context.OperationContext.UserCancellationToken); // If the last line isn't empty in the existing submission buffer, we will prepend a // newline var lastLine = buffer.CurrentSnapshot.GetLineFromLineNumber(buffer.CurrentSnapshot.LineCount - 1); if (lastLine.Extent.Length > 0) { var editorOptions = _editorOptionsService.Factory.GetOptions(args.SubjectBuffer); text = editorOptions.GetNewLineCharacter() + text; } edit.Insert(buffer.CurrentSnapshot.Length, text); edit.Apply(); } // Move the caret to the end var editorOperations = _editorOperationsFactoryService.GetEditorOperations(window.TextView); var endPoint = new VirtualSnapshotPoint(window.TextView.TextBuffer.CurrentSnapshot, window.TextView.TextBuffer.CurrentSnapshot.Length); editorOperations.SelectAndMoveCaret(endPoint, endPoint); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using System.Threading; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Interactive { internal abstract class InteractiveCommandHandler : ICommandHandler<ExecuteInInteractiveCommandArgs>, ICommandHandler<CopyToInteractiveCommandArgs> { private readonly IContentTypeRegistryService _contentTypeRegistryService; private readonly EditorOptionsService _editorOptionsService; private readonly IEditorOperationsFactoryService _editorOperationsFactoryService; protected InteractiveCommandHandler( IContentTypeRegistryService contentTypeRegistryService, EditorOptionsService editorOptionsService, IEditorOperationsFactoryService editorOperationsFactoryService) { _contentTypeRegistryService = contentTypeRegistryService; _editorOptionsService = editorOptionsService; _editorOperationsFactoryService = editorOperationsFactoryService; } protected IContentTypeRegistryService ContentTypeRegistryService { get { return _contentTypeRegistryService; } } protected abstract IInteractiveWindow OpenInteractiveWindow(bool focus); protected abstract ISendToInteractiveSubmissionProvider SendToInteractiveSubmissionProvider { get; } public string DisplayName => EditorFeaturesResources.Interactive; private string GetSelectedText(EditorCommandArgs args, CancellationToken cancellationToken) { var editorOptions = _editorOptionsService.Factory.GetOptions(args.SubjectBuffer); return SendToInteractiveSubmissionProvider.GetSelectedText(editorOptions, args, cancellationToken); } CommandState ICommandHandler<ExecuteInInteractiveCommandArgs>.GetCommandState(ExecuteInInteractiveCommandArgs args) => CommandState.Available; bool ICommandHandler<ExecuteInInteractiveCommandArgs>.ExecuteCommand(ExecuteInInteractiveCommandArgs args, CommandExecutionContext context) { var window = OpenInteractiveWindow(focus: false); using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesWpfResources.Executing_selection_in_Interactive_Window)) { var submission = GetSelectedText(args, context.OperationContext.UserCancellationToken); if (!string.IsNullOrWhiteSpace(submission)) { window.SubmitAsync(new string[] { submission }); } } return true; } CommandState ICommandHandler<CopyToInteractiveCommandArgs>.GetCommandState(CopyToInteractiveCommandArgs args) => CommandState.Available; bool ICommandHandler<CopyToInteractiveCommandArgs>.ExecuteCommand(CopyToInteractiveCommandArgs args, CommandExecutionContext context) { var window = OpenInteractiveWindow(focus: true); var buffer = window.CurrentLanguageBuffer; if (buffer != null) { CopyToWindow(window, args, context); } else { Action action = null; action = new Action(() => { window.ReadyForInput -= action; CopyToWindow(window, args, context); }); window.ReadyForInput += action; } return true; } private void CopyToWindow(IInteractiveWindow window, CopyToInteractiveCommandArgs args, CommandExecutionContext context) { var buffer = window.CurrentLanguageBuffer; Debug.Assert(buffer != null); using (var edit = buffer.CreateEdit()) using (var waitScope = context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesWpfResources.Copying_selection_to_Interactive_Window)) { var text = GetSelectedText(args, context.OperationContext.UserCancellationToken); // If the last line isn't empty in the existing submission buffer, we will prepend a // newline var lastLine = buffer.CurrentSnapshot.GetLineFromLineNumber(buffer.CurrentSnapshot.LineCount - 1); if (lastLine.Extent.Length > 0) { var editorOptions = _editorOptionsService.Factory.GetOptions(args.SubjectBuffer); text = editorOptions.GetNewLineCharacter() + text; } edit.Insert(buffer.CurrentSnapshot.Length, text); edit.Apply(); } // Move the caret to the end var editorOperations = _editorOperationsFactoryService.GetEditorOperations(window.TextView); var endPoint = new VirtualSnapshotPoint(window.TextView.TextBuffer.CurrentSnapshot, window.TextView.TextBuffer.CurrentSnapshot.Length); editorOperations.SelectAndMoveCaret(endPoint, endPoint); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpReplIdeFeatures.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpReplIdeFeatures : AbstractInteractiveWindowTest { public CSharpReplIdeFeatures(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override Task DisposeAsync() { VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.InteractiveWindow.ClearReplText(); VisualStudio.InteractiveWindow.Reset(); return base.DisposeAsync(); } [WpfFact] public void VerifyDefaultUsingStatements() { VisualStudio.InteractiveWindow.SubmitText("Console.WriteLine(42);"); VisualStudio.InteractiveWindow.WaitForLastReplOutput("42"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void VerifyCodeActionsNotAvailableInPreviousSubmission() { VisualStudio.InteractiveWindow.InsertCode("Console.WriteLine(42);"); VisualStudio.InteractiveWindow.Verify.CodeActionsNotShowing(); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void VerifyQuickInfoOnStringDocCommentsFromMetadata() { VisualStudio.InteractiveWindow.InsertCode("static void Goo(string[] args) { }"); VisualStudio.InteractiveWindow.PlaceCaret("[]", charsOffset: -2); VisualStudio.InteractiveWindow.InvokeQuickInfo(); var s = VisualStudio.InteractiveWindow.GetQuickInfo(); Assert.Equal("class System.String", s); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void International() { VisualStudio.InteractiveWindow.InsertCode(@"delegate void العربية(); العربية func = () => System.Console.WriteLine(2);"); VisualStudio.InteractiveWindow.PlaceCaret("func", charsOffset: -1); VisualStudio.InteractiveWindow.InvokeQuickInfo(); var s = VisualStudio.InteractiveWindow.GetQuickInfo(); Assert.Equal("(field) العربية func", s); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void HighlightRefsSingleSubmissionVerifyRenameTagsShowUpWhenInvokedOnUnsubmittedText() { VisualStudio.InteractiveWindow.InsertCode("int someint; someint = 22; someint = 23;"); VisualStudio.InteractiveWindow.PlaceCaret("someint = 22", charsOffset: -6); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 2); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void HighlightRefsSingleSubmissionVerifyRenameTagsGoAway() { VisualStudio.InteractiveWindow.InsertCode("int someint; someint = 22; someint = 23;"); VisualStudio.InteractiveWindow.PlaceCaret("someint = 22", charsOffset: -6); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 2); VisualStudio.InteractiveWindow.PlaceCaret("22"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 0); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 0); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpWhenInvokedOnSubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo something = new Goo();"); VisualStudio.InteractiveWindow.SubmitText("something.ToString();"); VisualStudio.InteractiveWindow.PlaceCaret("someth", charsOffset: 1, occurrence: 2); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 1); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnUnsubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo something = new Goo();"); VisualStudio.InteractiveWindow.InsertCode("something.ToString();"); VisualStudio.InteractiveWindow.PlaceCaret("someth", charsOffset: 1, occurrence: 2); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 1); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnTypesWhenInvokedOnSubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo a;"); VisualStudio.InteractiveWindow.SubmitText("Goo b;"); VisualStudio.InteractiveWindow.PlaceCaret("Goo b", charsOffset: -1); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 2); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnTypesWhenInvokedOnUnsubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo a;"); VisualStudio.InteractiveWindow.InsertCode("Goo b;"); VisualStudio.InteractiveWindow.PlaceCaret("Goo b", charsOffset: -1); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 2); } [WpfFact] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsGoAwayWhenInvokedOnUnsubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo a;"); VisualStudio.InteractiveWindow.InsertCode("Goo b;Something();"); VisualStudio.InteractiveWindow.PlaceCaret("Something();", charsOffset: -1); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 0); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0); } [WpfFact] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsOnRedefinedVariable() { VisualStudio.InteractiveWindow.SubmitText("string abc = null;"); VisualStudio.InteractiveWindow.SubmitText("abc = string.Empty;"); VisualStudio.InteractiveWindow.InsertCode("int abc = 42;"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.PlaceCaret("abc", occurrence: 3); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void DisabledCommandsPart1() { VisualStudio.InteractiveWindow.InsertCode(@"public class Class { int field; public void Method(int x) { int abc = 1 + 1; } }"); VisualStudio.InteractiveWindow.PlaceCaret("abc"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_Rename)); VisualStudio.InteractiveWindow.PlaceCaret("1 + 1"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ExtractMethod)); VisualStudio.InteractiveWindow.PlaceCaret("Class"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ExtractInterface)); VisualStudio.InteractiveWindow.PlaceCaret("field"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_EncapsulateField)); VisualStudio.InteractiveWindow.PlaceCaret("Method"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_RemoveParameters)); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ReorderParameters)); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void AddUsing() { VisualStudio.InteractiveWindow.InsertCode("typeof(ArrayList)"); VisualStudio.InteractiveWindow.PlaceCaret("ArrayList"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.InvokeCodeActionList(); VisualStudio.InteractiveWindow.Verify.CodeActions( new string[] { "using System.Collections;", "System.Collections.ArrayList" }, "using System.Collections;"); VisualStudio.InteractiveWindow.Verify.LastReplInput(@"using System.Collections; typeof(ArrayList)"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void QualifyName() { VisualStudio.InteractiveWindow.InsertCode("typeof(ArrayList)"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.PlaceCaret("ArrayList"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.Verify.CodeActions( new string[] { "using System.Collections;", "System.Collections.ArrayList" }, "System.Collections.ArrayList"); VisualStudio.InteractiveWindow.Verify.LastReplInput("typeof(System.Collections.ArrayList)"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpReplIdeFeatures : AbstractInteractiveWindowTest { public CSharpReplIdeFeatures(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override Task DisposeAsync() { VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.InteractiveWindow.ClearReplText(); VisualStudio.InteractiveWindow.Reset(); return base.DisposeAsync(); } [WpfFact] public void VerifyDefaultUsingStatements() { VisualStudio.InteractiveWindow.SubmitText("Console.WriteLine(42);"); VisualStudio.InteractiveWindow.WaitForLastReplOutput("42"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void VerifyCodeActionsNotAvailableInPreviousSubmission() { VisualStudio.InteractiveWindow.InsertCode("Console.WriteLine(42);"); VisualStudio.InteractiveWindow.Verify.CodeActionsNotShowing(); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void VerifyQuickInfoOnStringDocCommentsFromMetadata() { VisualStudio.InteractiveWindow.InsertCode("static void Goo(string[] args) { }"); VisualStudio.InteractiveWindow.PlaceCaret("[]", charsOffset: -2); VisualStudio.InteractiveWindow.InvokeQuickInfo(); var s = VisualStudio.InteractiveWindow.GetQuickInfo(); Assert.Equal("class System.String", s); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void International() { VisualStudio.InteractiveWindow.InsertCode(@"delegate void العربية(); العربية func = () => System.Console.WriteLine(2);"); VisualStudio.InteractiveWindow.PlaceCaret("func", charsOffset: -1); VisualStudio.InteractiveWindow.InvokeQuickInfo(); var s = VisualStudio.InteractiveWindow.GetQuickInfo(); Assert.Equal("(field) العربية func", s); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void HighlightRefsSingleSubmissionVerifyRenameTagsShowUpWhenInvokedOnUnsubmittedText() { VisualStudio.InteractiveWindow.InsertCode("int someint; someint = 22; someint = 23;"); VisualStudio.InteractiveWindow.PlaceCaret("someint = 22", charsOffset: -6); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 2); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void HighlightRefsSingleSubmissionVerifyRenameTagsGoAway() { VisualStudio.InteractiveWindow.InsertCode("int someint; someint = 22; someint = 23;"); VisualStudio.InteractiveWindow.PlaceCaret("someint = 22", charsOffset: -6); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 2); VisualStudio.InteractiveWindow.PlaceCaret("22"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 0); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 0); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpWhenInvokedOnSubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo something = new Goo();"); VisualStudio.InteractiveWindow.SubmitText("something.ToString();"); VisualStudio.InteractiveWindow.PlaceCaret("someth", charsOffset: 1, occurrence: 2); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 1); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnUnsubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo something = new Goo();"); VisualStudio.InteractiveWindow.InsertCode("something.ToString();"); VisualStudio.InteractiveWindow.PlaceCaret("someth", charsOffset: 1, occurrence: 2); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 1); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnTypesWhenInvokedOnSubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo a;"); VisualStudio.InteractiveWindow.SubmitText("Goo b;"); VisualStudio.InteractiveWindow.PlaceCaret("Goo b", charsOffset: -1); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 2); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnTypesWhenInvokedOnUnsubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo a;"); VisualStudio.InteractiveWindow.InsertCode("Goo b;"); VisualStudio.InteractiveWindow.PlaceCaret("Goo b", charsOffset: -1); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 2); } [WpfFact] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsGoAwayWhenInvokedOnUnsubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo a;"); VisualStudio.InteractiveWindow.InsertCode("Goo b;Something();"); VisualStudio.InteractiveWindow.PlaceCaret("Something();", charsOffset: -1); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 0); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0); } [WpfFact] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsOnRedefinedVariable() { VisualStudio.InteractiveWindow.SubmitText("string abc = null;"); VisualStudio.InteractiveWindow.SubmitText("abc = string.Empty;"); VisualStudio.InteractiveWindow.InsertCode("int abc = 42;"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.PlaceCaret("abc", occurrence: 3); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void DisabledCommandsPart1() { VisualStudio.InteractiveWindow.InsertCode(@"public class Class { int field; public void Method(int x) { int abc = 1 + 1; } }"); VisualStudio.InteractiveWindow.PlaceCaret("abc"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_Rename)); VisualStudio.InteractiveWindow.PlaceCaret("1 + 1"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ExtractMethod)); VisualStudio.InteractiveWindow.PlaceCaret("Class"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ExtractInterface)); VisualStudio.InteractiveWindow.PlaceCaret("field"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_EncapsulateField)); VisualStudio.InteractiveWindow.PlaceCaret("Method"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_RemoveParameters)); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ReorderParameters)); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void AddUsing() { VisualStudio.InteractiveWindow.InsertCode("typeof(ArrayList)"); VisualStudio.InteractiveWindow.PlaceCaret("ArrayList"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.InvokeCodeActionList(); VisualStudio.InteractiveWindow.Verify.CodeActions( new string[] { "using System.Collections;", "System.Collections.ArrayList" }, "using System.Collections;"); VisualStudio.InteractiveWindow.Verify.LastReplInput(@"using System.Collections; typeof(ArrayList)"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void QualifyName() { VisualStudio.InteractiveWindow.InsertCode("typeof(ArrayList)"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.PlaceCaret("ArrayList"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.Verify.CodeActions( new string[] { "using System.Collections;", "System.Collections.ArrayList" }, "System.Collections.ArrayList"); VisualStudio.InteractiveWindow.Verify.LastReplInput("typeof(System.Collections.ArrayList)"); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/Test/Utilities/AsynchronousOperationListenerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { public class AsynchronousOperationListenerTests { /// <summary> /// A delay which is not expected to be reached in practice. /// </summary> private static readonly TimeSpan s_unexpectedDelay = TimeSpan.FromSeconds(60); private class SleepHelper : IDisposable { private readonly CancellationTokenSource _tokenSource; private readonly List<Task> _tasks = new List<Task>(); public SleepHelper() => _tokenSource = new CancellationTokenSource(); public void Dispose() { Task[] tasks; lock (_tasks) { _tokenSource.Cancel(); tasks = _tasks.ToArray(); } try { Task.WaitAll(tasks); } catch (AggregateException e) { foreach (var inner in e.InnerExceptions) { Assert.IsType<TaskCanceledException>(inner); } } GC.SuppressFinalize(this); } public void Sleep(TimeSpan timeToSleep) { Task task; lock (_tasks) { task = Task.Factory.StartNew(() => { while (true) { _tokenSource.Token.ThrowIfCancellationRequested(); Thread.Sleep(TimeSpan.FromMilliseconds(10)); } }, _tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); _tasks.Add(task); } task.Wait((int)timeToSleep.TotalMilliseconds); } } [Fact] public void Operation() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = false; var asyncToken = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromSeconds(1)); done = true; }); task.CompletesAsyncOperation(asyncToken); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done, "The operation should have completed"); } [Fact] public void QueuedOperation() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); done = true; }); queuedTask.CompletesAsyncOperation(asyncToken2); queuedTask.Start(TaskScheduler.Default); }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done, "Should have waited for the queued operation to finish!"); } [Fact] public void Cancel() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = false; var continued = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { sleepHelper.Sleep(s_unexpectedDelay); continued = true; }); asyncToken2.Dispose(); queuedTask.Start(TaskScheduler.Default); done = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done, "Cancelling should have completed the current task."); Assert.False(continued, "Continued Task when it shouldn't have."); } [Fact] public void Nested() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var outerDone = false; var innerDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); using (listener.BeginAsyncOperation("Test")) { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); innerDone = true; } sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); outerDone = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(innerDone, "Should have completed the inner task"); Assert.True(outerDone, "Should have completed the outer task"); } [Fact] public void MultipleEnqueues() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var outerDone = false; var firstQueuedDone = false; var secondQueuedDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var firstQueueTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken3 = listener.BeginAsyncOperation("Test"); var secondQueueTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); secondQueuedDone = true; }); secondQueueTask.CompletesAsyncOperation(asyncToken3); secondQueueTask.Start(TaskScheduler.Default); firstQueuedDone = true; }); firstQueueTask.CompletesAsyncOperation(asyncToken2); firstQueueTask.Start(TaskScheduler.Default); outerDone = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(outerDone, "The outer task should have finished!"); Assert.True(firstQueuedDone, "The first queued task should have finished"); Assert.True(secondQueuedDone, "The second queued task should have finished"); } [Fact] public void IgnoredCancel() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = new TaskCompletionSource<VoidResult>(); var queuedFinished = new TaskCompletionSource<VoidResult>(); var cancelledFinished = new TaskCompletionSource<VoidResult>(); var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { using (listener.BeginAsyncOperation("Test")) { var cancelledTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromSeconds(10)); cancelledFinished.SetResult(default); }); signal.Set(); cancelledTask.Start(TaskScheduler.Default); } // Now that we've canceled the first request, queue another one to make sure we wait for it. var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { queuedFinished.SetResult(default); }); queuedTask.CompletesAsyncOperation(asyncToken2); queuedTask.Start(TaskScheduler.Default); done.SetResult(default); }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done.Task.IsCompleted, "Cancelling should have completed the current task."); Assert.True(queuedFinished.Task.IsCompleted, "Continued didn't run, but it was supposed to ignore the cancel."); Assert.False(cancelledFinished.Task.IsCompleted, "We waited for the cancelled task to finish."); } [Fact] public void SecondCompletion() { using var sleepHelper = new SleepHelper(); var signal1 = new ManualResetEventSlim(); var signal2 = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var firstDone = false; var secondDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var firstTask = Task.Factory.StartNew(() => { signal1.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); firstDone = true; }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); firstTask.CompletesAsyncOperation(asyncToken1); firstTask.Wait(); var asyncToken2 = listener.BeginAsyncOperation("Test"); var secondTask = Task.Factory.StartNew(() => { signal2.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); secondDone = true; }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); secondTask.CompletesAsyncOperation(asyncToken2); // give it two signals since second one might not have started when WaitTask.Wait is called - race condition Wait(listener, signal1, signal2); Assert.True(firstDone, "First didn't finish"); Assert.True(secondDone, "Should have waited for the second task"); } private static void Wait(AsynchronousOperationListener listener, ManualResetEventSlim signal) { // Note: WaitTask will return immediately if there is no outstanding work. Due to // threadpool scheduling, we may get here before that other thread has started to run. // That's why each task set's a signal to say that it has begun and we first wait for // that, and then start waiting. Assert.True(signal.Wait(s_unexpectedDelay), "Shouldn't have hit timeout waiting for task to begin"); var waitTask = listener.ExpeditedWaitAsync(); Assert.True(waitTask.Wait(s_unexpectedDelay), "Wait shouldn't have needed to timeout"); } private static void Wait(AsynchronousOperationListener listener, ManualResetEventSlim signal1, ManualResetEventSlim signal2) { // Note: WaitTask will return immediately if there is no outstanding work. Due to // threadpool scheduling, we may get here before that other thread has started to run. // That's why each task set's a signal to say that it has begun and we first wait for // that, and then start waiting. Assert.True(signal1.Wait(s_unexpectedDelay), "Shouldn't have hit timeout waiting for task to begin"); Assert.True(signal2.Wait(s_unexpectedDelay), "Shouldn't have hit timeout waiting for task to begin"); var waitTask = listener.ExpeditedWaitAsync(); Assert.True(waitTask.Wait(s_unexpectedDelay), "Wait shouldn't have needed to timeout"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { public class AsynchronousOperationListenerTests { /// <summary> /// A delay which is not expected to be reached in practice. /// </summary> private static readonly TimeSpan s_unexpectedDelay = TimeSpan.FromSeconds(60); private class SleepHelper : IDisposable { private readonly CancellationTokenSource _tokenSource; private readonly List<Task> _tasks = new List<Task>(); public SleepHelper() => _tokenSource = new CancellationTokenSource(); public void Dispose() { Task[] tasks; lock (_tasks) { _tokenSource.Cancel(); tasks = _tasks.ToArray(); } try { Task.WaitAll(tasks); } catch (AggregateException e) { foreach (var inner in e.InnerExceptions) { Assert.IsType<TaskCanceledException>(inner); } } GC.SuppressFinalize(this); } public void Sleep(TimeSpan timeToSleep) { Task task; lock (_tasks) { task = Task.Factory.StartNew(() => { while (true) { _tokenSource.Token.ThrowIfCancellationRequested(); Thread.Sleep(TimeSpan.FromMilliseconds(10)); } }, _tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); _tasks.Add(task); } task.Wait((int)timeToSleep.TotalMilliseconds); } } [Fact] public void Operation() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = false; var asyncToken = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromSeconds(1)); done = true; }); task.CompletesAsyncOperation(asyncToken); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done, "The operation should have completed"); } [Fact] public void QueuedOperation() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); done = true; }); queuedTask.CompletesAsyncOperation(asyncToken2); queuedTask.Start(TaskScheduler.Default); }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done, "Should have waited for the queued operation to finish!"); } [Fact] public void Cancel() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = false; var continued = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { sleepHelper.Sleep(s_unexpectedDelay); continued = true; }); asyncToken2.Dispose(); queuedTask.Start(TaskScheduler.Default); done = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done, "Cancelling should have completed the current task."); Assert.False(continued, "Continued Task when it shouldn't have."); } [Fact] public void Nested() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var outerDone = false; var innerDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); using (listener.BeginAsyncOperation("Test")) { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); innerDone = true; } sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); outerDone = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(innerDone, "Should have completed the inner task"); Assert.True(outerDone, "Should have completed the outer task"); } [Fact] public void MultipleEnqueues() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var outerDone = false; var firstQueuedDone = false; var secondQueuedDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var firstQueueTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken3 = listener.BeginAsyncOperation("Test"); var secondQueueTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); secondQueuedDone = true; }); secondQueueTask.CompletesAsyncOperation(asyncToken3); secondQueueTask.Start(TaskScheduler.Default); firstQueuedDone = true; }); firstQueueTask.CompletesAsyncOperation(asyncToken2); firstQueueTask.Start(TaskScheduler.Default); outerDone = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(outerDone, "The outer task should have finished!"); Assert.True(firstQueuedDone, "The first queued task should have finished"); Assert.True(secondQueuedDone, "The second queued task should have finished"); } [Fact] public void IgnoredCancel() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = new TaskCompletionSource<VoidResult>(); var queuedFinished = new TaskCompletionSource<VoidResult>(); var cancelledFinished = new TaskCompletionSource<VoidResult>(); var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { using (listener.BeginAsyncOperation("Test")) { var cancelledTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromSeconds(10)); cancelledFinished.SetResult(default); }); signal.Set(); cancelledTask.Start(TaskScheduler.Default); } // Now that we've canceled the first request, queue another one to make sure we wait for it. var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { queuedFinished.SetResult(default); }); queuedTask.CompletesAsyncOperation(asyncToken2); queuedTask.Start(TaskScheduler.Default); done.SetResult(default); }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done.Task.IsCompleted, "Cancelling should have completed the current task."); Assert.True(queuedFinished.Task.IsCompleted, "Continued didn't run, but it was supposed to ignore the cancel."); Assert.False(cancelledFinished.Task.IsCompleted, "We waited for the cancelled task to finish."); } [Fact] public void SecondCompletion() { using var sleepHelper = new SleepHelper(); var signal1 = new ManualResetEventSlim(); var signal2 = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var firstDone = false; var secondDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var firstTask = Task.Factory.StartNew(() => { signal1.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); firstDone = true; }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); firstTask.CompletesAsyncOperation(asyncToken1); firstTask.Wait(); var asyncToken2 = listener.BeginAsyncOperation("Test"); var secondTask = Task.Factory.StartNew(() => { signal2.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); secondDone = true; }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); secondTask.CompletesAsyncOperation(asyncToken2); // give it two signals since second one might not have started when WaitTask.Wait is called - race condition Wait(listener, signal1, signal2); Assert.True(firstDone, "First didn't finish"); Assert.True(secondDone, "Should have waited for the second task"); } private static void Wait(AsynchronousOperationListener listener, ManualResetEventSlim signal) { // Note: WaitTask will return immediately if there is no outstanding work. Due to // threadpool scheduling, we may get here before that other thread has started to run. // That's why each task set's a signal to say that it has begun and we first wait for // that, and then start waiting. Assert.True(signal.Wait(s_unexpectedDelay), "Shouldn't have hit timeout waiting for task to begin"); var waitTask = listener.ExpeditedWaitAsync(); Assert.True(waitTask.Wait(s_unexpectedDelay), "Wait shouldn't have needed to timeout"); } private static void Wait(AsynchronousOperationListener listener, ManualResetEventSlim signal1, ManualResetEventSlim signal2) { // Note: WaitTask will return immediately if there is no outstanding work. Due to // threadpool scheduling, we may get here before that other thread has started to run. // That's why each task set's a signal to say that it has begun and we first wait for // that, and then start waiting. Assert.True(signal1.Wait(s_unexpectedDelay), "Shouldn't have hit timeout waiting for task to begin"); Assert.True(signal2.Wait(s_unexpectedDelay), "Shouldn't have hit timeout waiting for task to begin"); var waitTask = listener.ExpeditedWaitAsync(); Assert.True(waitTask.Wait(s_unexpectedDelay), "Wait shouldn't have needed to timeout"); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Analyzers/CSharp/Tests/RemoveConfusingSuppression/RemoveConfusingSuppressionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.RemoveConfusingSuppression; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Confusing { using VerifyCS = CSharpCodeFixVerifier<CSharpRemoveConfusingSuppressionDiagnosticAnalyzer, CSharpRemoveConfusingSuppressionCodeFixProvider>; public class RemoveConfusingSuppressionTests { [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestRemoveWithIsExpression1() { await VerifyCS.VerifyCodeFixAsync( @" class C { void M(object o) { if (o [|!|]is string) { } } }", @" class C { void M(object o) { if (o is string) { } } }"); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestRemoveWithIsPattern1() { await VerifyCS.VerifyCodeFixAsync( @" class C { void M(object o) { if (o [|!|]is string s) { } } }", @" class C { void M(object o) { if (o is string s) { } } }"); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestNegateWithIsExpression_CSharp8() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string) { } } }", FixedCode = @" class C { void M(object o) { if (!(o is string)) { } } }", CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp8 }.RunAsync(); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestNegateWithIsPattern_CSharp8() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string s) { } } }", FixedCode = @" class C { void M(object o) { if (!(o is string s)) { } } }", CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestNegateWithIsExpression_CSharp9() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string) { } } }", FixedCode = @" class C { void M(object o) { if (o is not string) { } } }", CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestNegateWithIsPattern_CSharp9() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string s) { } } }", FixedState = { Sources = { @" class C { void M(object o) { if (o is not string s) { } } }" }, }, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestRemoveWithIsExpression_FixAll1() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string) { } if (o [|!|]is string) { } } }", FixedCode = @" class C { void M(object o) { if (o is string) { } if (o is string) { } } }", NumberOfFixAllIterations = 1, CodeActionEquivalenceKey = CSharpRemoveConfusingSuppressionCodeFixProvider.RemoveOperator, }.RunAsync(); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestNegateWithIsExpression_FixAll1() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string) { } if (o [|!|]is string) { } } }", FixedCode = @" class C { void M(object o) { if (!(o is string)) { } if (!(o is string)) { } } }", CodeActionIndex = 1, CodeActionEquivalenceKey = CSharpRemoveConfusingSuppressionCodeFixProvider.NegateExpression, NumberOfFixAllIterations = 1, }.RunAsync(); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestRemoveWithIsPatternExpression_FixAll1() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string s) { } if (o [|!|]is string t) { } } }", FixedCode = @" class C { void M(object o) { if (o is string s) { } if (o is string t) { } } }", NumberOfFixAllIterations = 1, CodeActionEquivalenceKey = CSharpRemoveConfusingSuppressionCodeFixProvider.RemoveOperator, }.RunAsync(); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestNegateWithIsPatternExpression_FixAll1() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string s) { } if (o [|!|]is string t) { } } }", FixedCode = @" class C { void M(object o) { if (!(o is string s)) { } if (!(o is string t)) { } } }", NumberOfFixAllIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = CSharpRemoveConfusingSuppressionCodeFixProvider.NegateExpression, }.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.RemoveConfusingSuppression; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Confusing { using VerifyCS = CSharpCodeFixVerifier<CSharpRemoveConfusingSuppressionDiagnosticAnalyzer, CSharpRemoveConfusingSuppressionCodeFixProvider>; public class RemoveConfusingSuppressionTests { [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestRemoveWithIsExpression1() { await VerifyCS.VerifyCodeFixAsync( @" class C { void M(object o) { if (o [|!|]is string) { } } }", @" class C { void M(object o) { if (o is string) { } } }"); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestRemoveWithIsPattern1() { await VerifyCS.VerifyCodeFixAsync( @" class C { void M(object o) { if (o [|!|]is string s) { } } }", @" class C { void M(object o) { if (o is string s) { } } }"); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestNegateWithIsExpression_CSharp8() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string) { } } }", FixedCode = @" class C { void M(object o) { if (!(o is string)) { } } }", CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp8 }.RunAsync(); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestNegateWithIsPattern_CSharp8() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string s) { } } }", FixedCode = @" class C { void M(object o) { if (!(o is string s)) { } } }", CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestNegateWithIsExpression_CSharp9() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string) { } } }", FixedCode = @" class C { void M(object o) { if (o is not string) { } } }", CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestNegateWithIsPattern_CSharp9() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string s) { } } }", FixedState = { Sources = { @" class C { void M(object o) { if (o is not string s) { } } }" }, }, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestRemoveWithIsExpression_FixAll1() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string) { } if (o [|!|]is string) { } } }", FixedCode = @" class C { void M(object o) { if (o is string) { } if (o is string) { } } }", NumberOfFixAllIterations = 1, CodeActionEquivalenceKey = CSharpRemoveConfusingSuppressionCodeFixProvider.RemoveOperator, }.RunAsync(); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestNegateWithIsExpression_FixAll1() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string) { } if (o [|!|]is string) { } } }", FixedCode = @" class C { void M(object o) { if (!(o is string)) { } if (!(o is string)) { } } }", CodeActionIndex = 1, CodeActionEquivalenceKey = CSharpRemoveConfusingSuppressionCodeFixProvider.NegateExpression, NumberOfFixAllIterations = 1, }.RunAsync(); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestRemoveWithIsPatternExpression_FixAll1() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string s) { } if (o [|!|]is string t) { } } }", FixedCode = @" class C { void M(object o) { if (o is string s) { } if (o is string t) { } } }", NumberOfFixAllIterations = 1, CodeActionEquivalenceKey = CSharpRemoveConfusingSuppressionCodeFixProvider.RemoveOperator, }.RunAsync(); } [Fact, WorkItem(44872, "https://github.com/dotnet/roslyn/issues/44872")] public async Task TestNegateWithIsPatternExpression_FixAll1() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o [|!|]is string s) { } if (o [|!|]is string t) { } } }", FixedCode = @" class C { void M(object o) { if (!(o is string s)) { } if (!(o is string t)) { } } }", NumberOfFixAllIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = CSharpRemoveConfusingSuppressionCodeFixProvider.NegateExpression, }.RunAsync(); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Nullability flow analysis. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed partial class NullableWalker : LocalDataFlowPass<NullableWalker.LocalState, NullableWalker.LocalFunctionState> { /// <summary> /// Nullable analysis data for methods, parameter default values, and attributes /// stored on the Compilation during testing only. /// The key is a symbol for methods or parameters, and syntax for attributes. /// </summary> internal sealed class NullableAnalysisData { internal readonly int MaxRecursionDepth; internal readonly ConcurrentDictionary<object, NullableWalker.Data> Data; internal NullableAnalysisData(int maxRecursionDepth = -1) { MaxRecursionDepth = maxRecursionDepth; Data = new ConcurrentDictionary<object, NullableWalker.Data>(); } } /// <summary> /// Used to copy variable slots and types from the NullableWalker for the containing method /// or lambda to the NullableWalker created for a nested lambda or local function. /// </summary> internal sealed class VariableState { // Consider referencing the Variables instance directly from the original NullableWalker // rather than cloning. (Items are added to the collections but never replaced so the // collections are lazily populated but otherwise immutable. We'd probably want a // clone when analyzing from speculative semantic model though.) internal readonly VariablesSnapshot Variables; // The nullable state of all variables captured at the point where the function or lambda appeared. internal readonly LocalStateSnapshot VariableNullableStates; internal VariableState(VariablesSnapshot variables, LocalStateSnapshot variableNullableStates) { Variables = variables; VariableNullableStates = variableNullableStates; } } /// <summary> /// Data recorded for a particular analysis run. /// </summary> internal readonly struct Data { /// <summary> /// Number of entries tracked during analysis. /// </summary> internal readonly int TrackedEntries; /// <summary> /// True if analysis was required; false if analysis was optional and results dropped. /// </summary> internal readonly bool RequiredAnalysis; internal Data(int trackedEntries, bool requiredAnalysis) { TrackedEntries = trackedEntries; RequiredAnalysis = requiredAnalysis; } } /// <summary> /// Represents the result of visiting an expression. /// Contains a result type which tells us whether the expression may be null, /// and an l-value type which tells us whether we can assign null to the expression. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] private readonly struct VisitResult { public readonly TypeWithState RValueType; public readonly TypeWithAnnotations LValueType; public VisitResult(TypeWithState rValueType, TypeWithAnnotations lValueType) { RValueType = rValueType; LValueType = lValueType; // https://github.com/dotnet/roslyn/issues/34993: Doesn't hold true for Tuple_Assignment_10. See if we can make it hold true //Debug.Assert((RValueType.Type is null && LValueType.TypeSymbol is null) || // RValueType.Type.Equals(LValueType.TypeSymbol, TypeCompareKind.ConsiderEverything | TypeCompareKind.AllIgnoreOptions)); } public VisitResult(TypeSymbol? type, NullableAnnotation annotation, NullableFlowState state) { RValueType = TypeWithState.Create(type, state); LValueType = TypeWithAnnotations.Create(type, annotation); Debug.Assert(TypeSymbol.Equals(RValueType.Type, LValueType.Type, TypeCompareKind.ConsiderEverything)); } internal string GetDebuggerDisplay() => $"{{LValue: {LValueType.GetDebuggerDisplay()}, RValue: {RValueType.GetDebuggerDisplay()}}}"; } /// <summary> /// Represents the result of visiting an argument expression. /// In addition to storing the <see cref="VisitResult"/>, also stores the <see cref="LocalState"/> /// for reanalyzing a lambda. /// </summary> [DebuggerDisplay("{VisitResult.GetDebuggerDisplay(), nq}")] private readonly struct VisitArgumentResult { public readonly VisitResult VisitResult; public readonly Optional<LocalState> StateForLambda; public TypeWithState RValueType => VisitResult.RValueType; public TypeWithAnnotations LValueType => VisitResult.LValueType; public VisitArgumentResult(VisitResult visitResult, Optional<LocalState> stateForLambda) { VisitResult = visitResult; StateForLambda = stateForLambda; } } private Variables _variables; /// <summary> /// Binder for symbol being analyzed. /// </summary> private readonly Binder _binder; /// <summary> /// Conversions with nullability and unknown matching any. /// </summary> private readonly Conversions _conversions; /// <summary> /// 'true' if non-nullable member warnings should be issued at return points. /// One situation where this is 'false' is when we are analyzing field initializers and there is a constructor symbol in the type. /// </summary> private readonly bool _useConstructorExitWarnings; /// <summary> /// If true, the parameter types and nullability from _delegateInvokeMethod is used for /// initial parameter state. If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeParameterTypes; /// <summary> /// If true, the return type and nullability from _delegateInvokeMethod is used. /// If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeReturnType; /// <summary> /// Method signature used for return or parameter types. Distinct from CurrentSymbol signature /// when CurrentSymbol is a lambda and type is inferred from MethodTypeInferrer. /// </summary> private MethodSymbol? _delegateInvokeMethod; /// <summary> /// Return statements and the result types from analyzing the returned expressions. Used when inferring lambda return type in MethodTypeInferrer. /// </summary> private ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? _returnTypesOpt; /// <summary> /// Invalid type, used only to catch Visit methods that do not set /// _result.Type. See VisitExpressionWithoutStackGuard. /// </summary> private static readonly TypeWithState _invalidType = TypeWithState.Create(ErrorTypeSymbol.UnknownResultType, NullableFlowState.NotNull); /// <summary> /// Contains the map of expressions to inferred nullabilities and types used by the optional rewriter phase of the /// compiler. /// </summary> private readonly ImmutableDictionary<BoundExpression, (NullabilityInfo Info, TypeSymbol? Type)>.Builder? _analyzedNullabilityMapOpt; /// <summary> /// Manages creating snapshots of the walker as appropriate. Null if we're not taking snapshots of /// this walker. /// </summary> private readonly SnapshotManager.Builder? _snapshotBuilderOpt; // https://github.com/dotnet/roslyn/issues/35043: remove this when all expression are supported private bool _disableNullabilityAnalysis; /// <summary> /// State of method group receivers, used later when analyzing the conversion to a delegate. /// (Could be replaced by _analyzedNullabilityMapOpt if that map is always available.) /// </summary> private PooledDictionary<BoundExpression, TypeWithState>? _methodGroupReceiverMapOpt; private PooledDictionary<BoundValuePlaceholderBase, (BoundExpression? Replacement, VisitResult Result)>? _resultForPlaceholdersOpt; /// <summary> /// Variables instances for each lambda or local function defined within the analyzed region. /// </summary> private PooledDictionary<MethodSymbol, Variables>? _nestedFunctionVariables; #if DEBUG private bool _completingTargetTypedExpression; #endif private PooledDictionary<BoundExpression, Func<TypeWithAnnotations, TypeWithState>>? _targetTypedAnalysisCompletionOpt; /// <summary> /// Map from a target-typed expression (such as a target-typed conditional, switch or new) to the delegate /// that completes analysis once the target type is known. /// The delegate is invoked by <see cref="VisitConversion(BoundConversion, BoundExpression, Conversion, TypeWithAnnotations, TypeWithState, bool, bool, bool, AssignmentKind, ParameterSymbol, bool, bool, bool, Optional&lt;LocalState&gt;,bool, Location, ArrayBuilder&lt;VisitResult&gt;)"/>. /// </summary> private PooledDictionary<BoundExpression, Func<TypeWithAnnotations, TypeWithState>> TargetTypedAnalysisCompletion => _targetTypedAnalysisCompletionOpt ??= PooledDictionary<BoundExpression, Func<TypeWithAnnotations, TypeWithState>>.GetInstance(); /// <summary> /// True if we're analyzing speculative code. This turns off some initialization steps /// that would otherwise be taken. /// </summary> private readonly bool _isSpeculative; /// <summary> /// True if this walker was created using an initial state. /// </summary> private readonly bool _hasInitialState; private readonly MethodSymbol? _baseOrThisInitializer; #if DEBUG /// <summary> /// Contains the expressions that should not be inserted into <see cref="_analyzedNullabilityMapOpt"/>. /// </summary> private static readonly ImmutableArray<BoundKind> s_skippedExpressions = ImmutableArray.Create(BoundKind.ArrayInitialization, BoundKind.ObjectInitializerExpression, BoundKind.CollectionInitializerExpression, BoundKind.DynamicCollectionElementInitializer); #endif /// <summary> /// The result and l-value type of the last visited expression. /// </summary> private VisitResult _visitResult; /// <summary> /// The visit result of the receiver for the current conditional access. /// /// For example: A conditional invocation uses a placeholder as a receiver. By storing the /// visit result from the actual receiver ahead of time, we can give this placeholder a correct result. /// </summary> private VisitResult _currentConditionalReceiverVisitResult; /// <summary> /// The result type represents the state of the last visited expression. /// </summary> private TypeWithState ResultType { get => _visitResult.RValueType; } private void SetResultType(BoundExpression? expression, TypeWithState type, bool updateAnalyzedNullability = true) { SetResult(expression, resultType: type, lvalueType: type.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: updateAnalyzedNullability); } private void SetAnalyzedNullability(BoundExpression? expression, TypeWithState type) { SetAnalyzedNullability(expression, resultType: type, lvalueType: type.ToTypeWithAnnotations(compilation)); } /// <summary> /// Force the inference of the LValueResultType from ResultType. /// </summary> private void UseRvalueOnly(BoundExpression? expression) { SetResult(expression, ResultType, ResultType.ToTypeWithAnnotations(compilation), isLvalue: false); } private TypeWithAnnotations LvalueResultType { get => _visitResult.LValueType; } private void SetLvalueResultType(BoundExpression? expression, TypeWithAnnotations type) { SetResult(expression, resultType: type.ToTypeWithState(), lvalueType: type); } /// <summary> /// Force the inference of the ResultType from LValueResultType. /// </summary> private void UseLvalueOnly(BoundExpression? expression) { SetResult(expression, LvalueResultType.ToTypeWithState(), LvalueResultType, isLvalue: true); } private void SetInvalidResult() => SetResult(expression: null, _invalidType, _invalidType.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: false); private void SetResult(BoundExpression? expression, TypeWithState resultType, TypeWithAnnotations lvalueType, bool updateAnalyzedNullability = true, bool? isLvalue = null) { _visitResult = new VisitResult(resultType, lvalueType); if (updateAnalyzedNullability) { SetAnalyzedNullability(expression, _visitResult, isLvalue); } } private void SetAnalyzedNullability(BoundExpression? expression, TypeWithState resultType, TypeWithAnnotations lvalueType, bool? isLvalue = null) { SetAnalyzedNullability(expression, new VisitResult(resultType, lvalueType), isLvalue); } private bool ShouldMakeNotNullRvalue(BoundExpression node) => node.IsSuppressed || node.HasAnyErrors || !IsReachable(); /// <summary> /// Sets the analyzed nullability of the expression to be the given result. /// </summary> private void SetAnalyzedNullability(BoundExpression? expr, VisitResult result, bool? isLvalue = null) { if (expr == null || _disableNullabilityAnalysis) return; #if DEBUG // https://github.com/dotnet/roslyn/issues/34993: This assert is essential for ensuring that we aren't // changing the observable results of GetTypeInfo beyond nullability information. //Debug.Assert(AreCloseEnough(expr.Type, result.RValueType.Type), // $"Cannot change the type of {expr} from {expr.Type} to {result.RValueType.Type}"); #endif if (_analyzedNullabilityMapOpt != null) { // https://github.com/dotnet/roslyn/issues/34993: enable and verify these assertions #if false if (_analyzedNullabilityMapOpt.TryGetValue(expr, out var existing)) { if (!(result.RValueType.State == NullableFlowState.NotNull && ShouldMakeNotNullRvalue(expr, State.Reachable))) { switch (isLvalue) { case true: Debug.Assert(existing.Info.Annotation == result.LValueType.NullableAnnotation.ToPublicAnnotation(), $"Tried to update the nullability of {expr} from {existing.Info.Annotation} to {result.LValueType.NullableAnnotation}"); break; case false: Debug.Assert(existing.Info.FlowState == result.RValueType.State, $"Tried to update the nullability of {expr} from {existing.Info.FlowState} to {result.RValueType.State}"); break; case null: Debug.Assert(existing.Info.Equals((NullabilityInfo)result), $"Tried to update the nullability of {expr} from ({existing.Info.Annotation}, {existing.Info.FlowState}) to ({result.LValueType.NullableAnnotation}, {result.RValueType.State})"); break; } } } #endif _analyzedNullabilityMapOpt[expr] = (new NullabilityInfo(result.LValueType.ToPublicAnnotation(), result.RValueType.State.ToPublicFlowState()), // https://github.com/dotnet/roslyn/issues/35046 We're dropping the result if the type doesn't match up completely // with the existing type expr.Type?.Equals(result.RValueType.Type, TypeCompareKind.AllIgnoreOptions) == true ? result.RValueType.Type : expr.Type); } } /// <summary> /// Placeholder locals, e.g. for objects being constructed. /// </summary> private PooledDictionary<object, PlaceholderLocal>? _placeholderLocalsOpt; /// <summary> /// For methods with annotations, we'll need to visit the arguments twice. /// Once for diagnostics and once for result state (but disabling diagnostics). /// </summary> private bool _disableDiagnostics = false; /// <summary> /// Whether we are going to read the currently visited expression. /// </summary> private bool _expressionIsRead = true; /// <summary> /// Used to allow <see cref="MakeSlot(BoundExpression)"/> to substitute the correct slot for a <see cref="BoundConditionalReceiver"/> when /// it's encountered. /// </summary> private int _lastConditionalAccessSlot = -1; private bool IsAnalyzingAttribute => methodMainNode.Kind == BoundKind.Attribute; protected override void Free() { AssertNoPlaceholderReplacements(); _nestedFunctionVariables?.Free(); _resultForPlaceholdersOpt?.Free(); _methodGroupReceiverMapOpt?.Free(); _placeholderLocalsOpt?.Free(); _variables.Free(); Debug.Assert(_targetTypedAnalysisCompletionOpt is null or { Count: 0 }); _targetTypedAnalysisCompletionOpt?.Free(); base.Free(); } private NullableWalker( CSharpCompilation compilation, Symbol? symbol, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, BoundNode node, Binder binder, Conversions conversions, Variables? variables, MethodSymbol? baseOrThisInitializer, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, bool isSpeculative = false) : base(compilation, symbol, node, EmptyStructTypeCache.CreatePrecise(), trackUnassignments: true) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethodOpt is object); Debug.Assert(baseOrThisInitializer is null or { MethodKind: MethodKind.Constructor }); _variables = variables ?? Variables.Create(symbol); _binder = binder; _conversions = (Conversions)conversions.WithNullability(true); _useConstructorExitWarnings = useConstructorExitWarnings; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; _delegateInvokeMethod = delegateInvokeMethodOpt; _analyzedNullabilityMapOpt = analyzedNullabilityMapOpt; _returnTypesOpt = returnTypesOpt; _snapshotBuilderOpt = snapshotBuilderOpt; _isSpeculative = isSpeculative; _hasInitialState = variables is { }; _baseOrThisInitializer = baseOrThisInitializer; } public string GetDebuggerDisplay() { if (this.IsConditionalState) { return $"{{{GetType().Name} WhenTrue:{Dump(StateWhenTrue)} WhenFalse:{Dump(StateWhenFalse)}{"}"}"; } else { return $"{{{GetType().Name} {Dump(State)}{"}"}"; } } // For purpose of nullability analysis, awaits create pending branches, so async usings and foreachs do too public sealed override bool AwaitUsingAndForeachAddsPendingBranch => true; protected override void EnsureSufficientExecutionStack(int recursionDepth) { if (recursionDepth > StackGuard.MaxUncheckedRecursionDepth && compilation.TestOnlyCompilationData is NullableAnalysisData { MaxRecursionDepth: var depth } && depth > 0 && recursionDepth > depth) { throw new InsufficientExecutionStackException(); } base.EnsureSufficientExecutionStack(recursionDepth); } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return true; } protected override bool TryGetVariable(VariableIdentifier identifier, out int slot) { return _variables.TryGetValue(identifier, out slot); } protected override int AddVariable(VariableIdentifier identifier) { return _variables.Add(identifier); } [Conditional("DEBUG")] private void AssertNoPlaceholderReplacements() { if (_resultForPlaceholdersOpt is not null) { Debug.Assert(_resultForPlaceholdersOpt.Count == 0); } } private void AddPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression? expression, VisitResult result) { #if DEBUG Debug.Assert(AreCloseEnough(placeholder.Type, result.RValueType.Type)); Debug.Assert(expression != null || placeholder.Kind == BoundKind.InterpolatedStringArgumentPlaceholder); #endif _resultForPlaceholdersOpt ??= PooledDictionary<BoundValuePlaceholderBase, (BoundExpression? Replacement, VisitResult Result)>.GetInstance(); _resultForPlaceholdersOpt.Add(placeholder, (expression, result)); } private void RemovePlaceholderReplacement(BoundValuePlaceholderBase placeholder) { Debug.Assert(_resultForPlaceholdersOpt is { }); bool removed = _resultForPlaceholdersOpt.Remove(placeholder); Debug.Assert(removed); } [Conditional("DEBUG")] private static void AssertPlaceholderAllowedWithoutRegistration(BoundValuePlaceholderBase placeholder) { Debug.Assert(placeholder is { }); switch (placeholder.Kind) { case BoundKind.DeconstructValuePlaceholder: case BoundKind.InterpolatedStringHandlerPlaceholder: case BoundKind.InterpolatedStringArgumentPlaceholder: case BoundKind.ObjectOrCollectionValuePlaceholder: case BoundKind.AwaitableValuePlaceholder: return; case BoundKind.ImplicitIndexerValuePlaceholder: // Since such placeholders are always not-null, we skip adding them to the map. return; default: // Newer placeholders are expected to follow placeholder discipline, namely that // they must be added to the map before they are visited, then removed. throw ExceptionUtilities.UnexpectedValue(placeholder.Kind); } } protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion) { if (_returnTypesOpt != null) { _returnTypesOpt.Clear(); } this.Diagnostics.Clear(); this.regionPlace = RegionPlace.Before; if (!_isSpeculative) { ParameterSymbol methodThisParameter = MethodThisParameter; EnterParameters(); // assign parameters if (methodThisParameter is object) { EnterParameter(methodThisParameter, methodThisParameter.TypeWithAnnotations); } makeNotNullMembersMaybeNull(); // We need to create a snapshot even of the first node, because we want to have the state of the initial parameters. _snapshotBuilderOpt?.TakeIncrementalSnapshot(methodMainNode, State); } ImmutableArray<PendingBranch> pendingReturns = base.Scan(ref badRegion); if ((_symbol as MethodSymbol)?.IsConstructor() != true || _useConstructorExitWarnings) { EnforceDoesNotReturn(syntaxOpt: null); enforceMemberNotNull(syntaxOpt: null, this.State); EnforceParameterNotNullOnExit(syntaxOpt: null, this.State); foreach (var pendingReturn in pendingReturns) { enforceMemberNotNull(syntaxOpt: pendingReturn.Branch.Syntax, pendingReturn.State); if (pendingReturn.Branch is BoundReturnStatement returnStatement) { EnforceParameterNotNullOnExit(returnStatement.Syntax, pendingReturn.State); EnforceNotNullWhenForPendingReturn(pendingReturn, returnStatement); enforceMemberNotNullWhenForPendingReturn(pendingReturn, returnStatement); } } } return pendingReturns; void enforceMemberNotNull(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } var method = _symbol as MethodSymbol; if (method is object) { if (method.IsConstructor()) { Debug.Assert(_useConstructorExitWarnings); var thisSlot = 0; if (method.RequiresInstanceReceiver) { method.TryGetThisParameter(out var thisParameter); Debug.Assert(thisParameter is object); thisSlot = GetOrCreateSlot(thisParameter); } // https://github.com/dotnet/roslyn/issues/46718: give diagnostics on return points, not constructor signature var exitLocation = method.DeclaringSyntaxReferences.IsEmpty ? null : method.Locations.FirstOrDefault(); foreach (var member in method.ContainingType.GetMembersUnordered()) { checkMemberStateOnConstructorExit(method, member, state, thisSlot, exitLocation); } } else { do { foreach (var memberName in method.NotNullMembers) { enforceMemberNotNullOnMember(syntaxOpt, state, method, memberName); } method = method.OverriddenMethod; } while (method != null); } } } void checkMemberStateOnConstructorExit(MethodSymbol constructor, Symbol member, LocalState state, int thisSlot, Location? exitLocation) { var isStatic = !constructor.RequiresInstanceReceiver(); if (member.IsStatic != isStatic) { return; } // This is not required for correctness, but in the case where the member has // an initializer, we know we've assigned to the member and // have given any applicable warnings about a bad value going in. // Therefore we skip this check when the member has an initializer to reduce noise. if (HasInitializer(member)) { return; } TypeWithAnnotations fieldType; FieldSymbol? field; Symbol symbol; switch (member) { case FieldSymbol f: fieldType = f.TypeWithAnnotations; field = f; symbol = (Symbol?)(f.AssociatedSymbol as PropertySymbol) ?? f; break; case EventSymbol e: fieldType = e.TypeWithAnnotations; field = e.AssociatedField; symbol = e; if (field is null) { return; } break; default: return; } if (field.IsConst) { return; } if (fieldType.Type.IsValueType || fieldType.Type.IsErrorType()) { return; } if (symbol.IsRequired() && constructor.ShouldCheckRequiredMembers()) { return; } var annotations = symbol.GetFlowAnalysisAnnotations(); if ((annotations & FlowAnalysisAnnotations.AllowNull) != 0) { // We assume that if a member has AllowNull then the user // does not care that we exit at a point where the member might be null. return; } fieldType = ApplyUnconditionalAnnotations(fieldType, annotations); if (!fieldType.NullableAnnotation.IsNotAnnotated()) { return; } var slot = GetOrCreateSlot(symbol, thisSlot); if (slot < 0) { return; } var memberState = state[slot]; var badState = fieldType.Type.IsPossiblyNullableReferenceTypeTypeParameter() && (annotations & FlowAnalysisAnnotations.NotNull) == 0 ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; if (memberState >= badState) // is 'memberState' as bad as or worse than 'badState'? { var info = new CSDiagnosticInfo(ErrorCode.WRN_UninitializedNonNullableField, new object[] { symbol.Kind.Localize(), symbol.Name }, ImmutableArray<Symbol>.Empty, additionalLocations: symbol.Locations); Diagnostics.Add(info, exitLocation ?? symbol.Locations.FirstOrNone()); } } void enforceMemberNotNullOnMember(SyntaxNode? syntaxOpt, LocalState state, MethodSymbol method, string memberName) { foreach (var member in method.ContainingType.GetMembers(memberName)) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_MemberNotNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name); } } } void enforceMemberNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } if (_symbol is MethodSymbol method) { foreach (var memberName in method.NotNullWhenTrueMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: true, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenTrue, pendingReturn.StateWhenFalse); } foreach (var memberName in method.NotNullWhenFalseMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: false, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenFalse, pendingReturn.StateWhenTrue); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); } } void enforceMemberNotNullWhenIfAffected(SyntaxNode? syntaxOpt, bool sense, ImmutableArray<Symbol> members, LocalState state, LocalState otherState) { foreach (var member in members) { // For non-constant values, only complain if we were able to analyze a difference for this member between two branches if (memberHasBadState(member, state) != memberHasBadState(member, otherState)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } void enforceMemberNotNullWhen(SyntaxNode? syntaxOpt, bool sense, LocalState state) { if (_symbol is MethodSymbol method) { var notNullMembers = sense ? method.NotNullWhenTrueMembers : method.NotNullWhenFalseMembers; foreach (var memberName in notNullMembers) { foreach (var member in method.ContainingType.GetMembers(memberName)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } } void reportMemberIfBadConditionalState(SyntaxNode? syntaxOpt, bool sense, Symbol member, LocalState state) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_MemberNotNullWhen, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name, sense ? "true" : "false"); } } bool memberHasBadState(Symbol member, LocalState state) { switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { var parameterState = state[memberSlot]; return !parameterState.IsNotNull(); } else { return false; } case SymbolKind.Event: case SymbolKind.Method: break; } return false; } void makeNotNullMembersMaybeNull() { if (_symbol is MethodSymbol method) { if (method.IsConstructor()) { foreach (var member in getMembersNeedingDefaultInitialState()) { if (member.IsStatic != method.IsStatic) { continue; } var memberToInitialize = member; switch (member) { case PropertySymbol: // skip any manually implemented properties. continue; case FieldSymbol { IsConst: true }: continue; case FieldSymbol { AssociatedSymbol: PropertySymbol prop }: // this is a property where assigning 'default' causes us to simply update // the state to the output state of the property // thus we skip setting an initial state for it here if (IsPropertyOutputMoreStrictThanInput(prop)) { continue; } // We want to initialize auto-property state to the default state, but not computed properties. memberToInitialize = prop; break; default: break; } var memberSlot = getSlotForFieldOrPropertyOrEvent(memberToInitialize); if (memberSlot > 0) { var type = memberToInitialize.GetTypeOrReturnType(); if (!type.NullableAnnotation.IsOblivious()) { this.State[memberSlot] = type.Type.IsPossiblyNullableReferenceTypeTypeParameter() ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } } else { do { makeMembersMaybeNull(method, method.NotNullMembers); makeMembersMaybeNull(method, method.NotNullWhenTrueMembers); makeMembersMaybeNull(method, method.NotNullWhenFalseMembers); method = method.OverriddenMethod; } while (method != null); } } return; ImmutableArray<Symbol> getMembersNeedingDefaultInitialState() { if (_hasInitialState) { return ImmutableArray<Symbol>.Empty; } bool includeCurrentTypeRequiredMembers = true; bool includeBaseRequiredMembers = true; bool hasThisConstructorInitializer = false; if (method is SourceMemberMethodSymbol { SyntaxNode: ConstructorDeclarationSyntax { Initializer: { RawKind: var initializerKind } } }) { // We have multiple ways of entering the nullable walker: we could be just analyzing the initializers, with a BoundStatementList body and _baseOrThisInitializer // having been provided, or we could be analyzing the body of a constructor, with a BoundConstructorBody body and _baseOrThisInitializer being null. var baseOrThisInitializer = (_baseOrThisInitializer ?? GetConstructorThisOrBaseSymbol(this.methodMainNode)); // If there's an error in the base or this initializer, presume that we should set all required members to default. includeBaseRequiredMembers = baseOrThisInitializer?.ShouldCheckRequiredMembers() ?? true; if (initializerKind == (int)SyntaxKind.ThisConstructorInitializer) { hasThisConstructorInitializer = true; // If we chained to a `this` constructor, a SetsRequiredMembers attribute applies to both the current type's required members and the base type's required members. includeCurrentTypeRequiredMembers = includeBaseRequiredMembers; } else if (initializerKind == (int)SyntaxKind.BaseConstructorInitializer) { // If we chained to a `base` constructor, a SetsRequiredMembers attribute applies to the base type's required members only, and the current type's required members // are not assumed to be initialized. includeCurrentTypeRequiredMembers = true; } } // Pre-C# 11, we don't use a default initial state for value type instance constructors without `: this()` // because any usages of uninitialized fields will get definite assignment errors anyway. if (!hasThisConstructorInitializer && (!method.ContainingType.IsValueType || method.IsStatic || compilation.IsFeatureEnabled(MessageID.IDS_FeatureAutoDefaultStructs))) { return membersToBeInitialized(method.ContainingType, includeAllMembers: true, includeCurrentTypeRequiredMembers, includeBaseRequiredMembers); } // We want to presume all required members of the type are uninitialized, and in addition we want to set all fields to // default if we can get to this constructor by doing so (ie, : this() in a value type). return membersToBeInitialized(method.ContainingType, includeAllMembers: method.IncludeFieldInitializersInBody(), includeCurrentTypeRequiredMembers, includeBaseRequiredMembers); static ImmutableArray<Symbol> membersToBeInitialized(NamedTypeSymbol containingType, bool includeAllMembers, bool includeCurrentTypeRequiredMembers, bool includeBaseRequiredMembers) { return (includeAllMembers, includeCurrentTypeRequiredMembers, includeBaseRequiredMembers) switch { (includeAllMembers: false, includeCurrentTypeRequiredMembers: false, includeBaseRequiredMembers: false) => ImmutableArray<Symbol>.Empty, (includeAllMembers: false, includeCurrentTypeRequiredMembers: true, includeBaseRequiredMembers: false) => containingType.GetMembersUnordered().SelectAsArray(predicate: SymbolExtensions.IsRequired, selector: getFieldSymbolToBeInitialized), (includeAllMembers: false, includeCurrentTypeRequiredMembers: true, includeBaseRequiredMembers: true) => containingType.AllRequiredMembers.SelectAsArray(static kvp => getFieldSymbolToBeInitialized(kvp.Value)), (includeAllMembers: true, includeCurrentTypeRequiredMembers: _, includeBaseRequiredMembers: false) => containingType.GetMembersUnordered().SelectAsArray(getFieldSymbolToBeInitialized), (includeAllMembers: true, includeCurrentTypeRequiredMembers: true, includeBaseRequiredMembers: true) => getAllTypeAndRequiredMembers(containingType), (includeAllMembers: _, includeCurrentTypeRequiredMembers: false, includeBaseRequiredMembers: true) => throw ExceptionUtilities.Unreachable, }; static ImmutableArray<Symbol> getAllTypeAndRequiredMembers(TypeSymbol containingType) { var members = containingType.GetMembersUnordered(); var requiredMembers = containingType.BaseTypeNoUseSiteDiagnostics?.AllRequiredMembers ?? ImmutableSegmentedDictionary<string, Symbol>.Empty; if (requiredMembers.IsEmpty) { return members; } var builder = ArrayBuilder<Symbol>.GetInstance(members.Length + requiredMembers.Count); builder.AddRange(members); foreach (var (_, requiredMember) in requiredMembers) { // We want to assume that all required members were _not_ set by the chained constructor builder.Add(getFieldSymbolToBeInitialized(requiredMember)); } return builder.ToImmutableAndFree(); } static Symbol getFieldSymbolToBeInitialized(Symbol requiredMember) => requiredMember is SourcePropertySymbol { IsAutoPropertyWithGetAccessor: true } prop ? prop.BackingField : requiredMember; } } } void makeMembersMaybeNull(MethodSymbol method, ImmutableArray<string> members) { foreach (var memberName in members) { makeMemberMaybeNull(method, memberName); } } void makeMemberMaybeNull(MethodSymbol method, string memberName) { var type = method.ContainingType; foreach (var member in type.GetMembers(memberName)) { if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { this.State[memberSlot] = NullableFlowState.MaybeNull; } } } int getSlotForFieldOrPropertyOrEvent(Symbol member) { if (member.Kind != SymbolKind.Field && member.Kind != SymbolKind.Property && member.Kind != SymbolKind.Event) { return -1; } int containingSlot = 0; if (!member.IsStatic) { if (MethodThisParameter is null) { return -1; } containingSlot = GetOrCreateSlot(MethodThisParameter); if (containingSlot < 0) { return -1; } Debug.Assert(containingSlot > 0); } return GetOrCreateSlot(member, containingSlot); } } private void EnforceNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { var parameters = this.MethodParameters; if (!parameters.IsEmpty) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { EnforceParameterNotNullWhenOnExit(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } foreach (var parameter in parameters) { // For non-constant values, only complain if we were able to analyze a difference for this parameter between two branches if (GetOrCreateSlot(parameter) is > 0 and var slot && pendingReturn.StateWhenTrue[slot] != pendingReturn.StateWhenFalse[slot]) { ReportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: true, stateWhen: pendingReturn.StateWhenTrue); ReportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: false, stateWhen: pendingReturn.StateWhenFalse); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { // example: return (bool)true; EnforceParameterNotNullWhenOnExit(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } } } private void EnforceParameterNotNullOnExit(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } foreach (var parameter in this.MethodParameters) { var slot = GetOrCreateSlot(parameter); if (slot <= 0) { continue; } var annotations = parameter.FlowAnalysisAnnotations; var hasNotNull = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; var parameterState = state[slot]; if (hasNotNull && parameterState.MayBeNull()) { Location location; if (syntaxOpt is BlockSyntax blockSyntax) { location = blockSyntax.CloseBraceToken.GetLocation(); } else { location = syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(); } // Parameter '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_ParameterDisallowsNull, location, parameter.Name); } else { EnforceNotNullIfNotNull(syntaxOpt, state, this.MethodParameters, parameter.NotNullIfParameterNotNull, parameterState, parameter); } } } private void EnforceParameterNotNullWhenOnExit(SyntaxNode syntax, ImmutableArray<ParameterSymbol> parameters, bool sense, LocalState stateWhen) { if (!stateWhen.Reachable) { return; } foreach (var parameter in parameters) { ReportParameterIfBadConditionalState(syntax, parameter, sense, stateWhen); } } private void ReportParameterIfBadConditionalState(SyntaxNode syntax, ParameterSymbol parameter, bool sense, LocalState stateWhen) { if (parameterHasBadConditionalState(parameter, sense, stateWhen)) { // Parameter '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_ParameterConditionallyDisallowsNull, syntax.Location, parameter.Name, sense ? "true" : "false"); } return; bool parameterHasBadConditionalState(ParameterSymbol parameter, bool sense, LocalState stateWhen) { var refKind = parameter.RefKind; if (refKind != RefKind.Out && refKind != RefKind.Ref) { return false; } var slot = GetOrCreateSlot(parameter); if (slot > 0) { var parameterState = stateWhen[slot]; // On a parameter marked with MaybeNullWhen, we would have not reported an assignment warning. // We should only check if an assignment warning would have been warranted ignoring the MaybeNullWhen. FlowAnalysisAnnotations annotations = parameter.FlowAnalysisAnnotations; if (sense) { bool hasNotNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenTrue; bool hasMaybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenFalse; return (hasNotNullWhenTrue && parameterState.MayBeNull()) || (hasMaybeNullWhenFalse && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } else { bool hasNotNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenFalse; bool hasMaybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenTrue; return (hasNotNullWhenFalse && parameterState.MayBeNull()) || (hasMaybeNullWhenTrue && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } } return false; } } private void EnforceNotNullIfNotNull(SyntaxNode? syntaxOpt, LocalState state, ImmutableArray<ParameterSymbol> parameters, ImmutableHashSet<string> inputParamNames, NullableFlowState outputState, ParameterSymbol? outputParam) { if (inputParamNames.IsEmpty || outputState.IsNotNull()) { return; } foreach (var inputParam in parameters) { if (inputParamNames.Contains(inputParam.Name) && GetOrCreateSlot(inputParam) is > 0 and int inputSlot && state[inputSlot].IsNotNull()) { var location = syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(); if (outputParam is object) { // Parameter '{0}' must have a non-null value when exiting because parameter '{1}' is non-null. Diagnostics.Add(ErrorCode.WRN_ParameterNotNullIfNotNull, location, outputParam.Name, inputParam.Name); } else if (CurrentSymbol is MethodSymbol { IsAsync: false }) { // Return value must be non-null because parameter '{0}' is non-null. Diagnostics.Add(ErrorCode.WRN_ReturnNotNullIfNotNull, location, inputParam.Name); } break; } } } private void EnforceDoesNotReturn(SyntaxNode? syntaxOpt) { if (CurrentSymbol is MethodSymbol method && ((method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) && this.IsReachable()) { // A method marked [DoesNotReturn] should not return. ReportDiagnostic(ErrorCode.WRN_ShouldNotReturn, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation()); } } /// <summary> /// Analyzes a method body if settings indicate we should. /// </summary> internal static void AnalyzeIfNeeded( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, MethodSymbol? baseOrThisInitializer, out VariableState? finalNullableState) { if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(method)) { if (compilation.IsNullableAnalysisEnabledAlways) { // Once we address https://github.com/dotnet/roslyn/issues/46579 we should also always pass `getFinalNullableState: true` in debug mode. // We will likely always need to write a 'null' out for the out parameter in this code path, though, because // we don't want to introduce behavior differences between debug and release builds Analyze(compilation, method, node, new DiagnosticBag(), useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: false, baseOrThisInitializer, out _, requiresAnalysis: false); } finalNullableState = null; return; } Analyze(compilation, method, node, diagnostics, useConstructorExitWarnings, initialNullableState, getFinalNullableState, baseOrThisInitializer, out finalNullableState); } private static void Analyze( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, MethodSymbol? baseOrThisInitializer, out VariableState? finalNullableState, bool requiresAnalysis = true) { if (method.IsImplicitlyDeclared && !method.IsImplicitConstructor && !method.IsScriptInitializer) { finalNullableState = null; return; } Debug.Assert(node.SyntaxTree is object); var binder = method is SynthesizedSimpleProgramEntryPointSymbol entryPoint ? entryPoint.GetBodyBinder(ignoreAccessibility: false) : compilation.GetBinderFactory(node.SyntaxTree).GetBinder(node.Syntax); var conversions = binder.Conversions; Analyze(compilation, method, node, binder, conversions, diagnostics, useConstructorExitWarnings, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: initialNullableState, baseOrThisInitializer, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState, finalNullableState: out finalNullableState, requiresAnalysis); } internal static VariableState? GetAfterInitializersState(CSharpCompilation compilation, Symbol? symbol, BoundNode constructorBody) { if (symbol is MethodSymbol method && method.IncludeFieldInitializersInBody() && method.ContainingType is SourceMemberContainerTypeSymbol containingType) { Binder.ProcessedFieldInitializers discardedInitializers = default; Binder.BindFieldInitializers(compilation, null, method.IsStatic ? containingType.StaticInitializers : containingType.InstanceInitializers, BindingDiagnosticBag.Discarded, ref discardedInitializers); return GetAfterInitializersState(compilation, method, InitializerRewriter.RewriteConstructor(discardedInitializers.BoundInitializers, method), constructorBody, diagnostics: BindingDiagnosticBag.Discarded); } return null; } /// <summary> /// Gets the "after initializers state" which should be used at the beginning of nullable analysis /// of certain constructors. /// </summary> internal static VariableState? GetAfterInitializersState(CSharpCompilation compilation, MethodSymbol method, BoundNode nodeToAnalyze, BoundNode? constructorBody, BindingDiagnosticBag diagnostics) { Debug.Assert(method.IsConstructor()); bool ownsDiagnostics; DiagnosticBag diagnosticsBag; if (diagnostics.DiagnosticBag == null) { diagnostics = BindingDiagnosticBag.Discarded; diagnosticsBag = DiagnosticBag.GetInstance(); ownsDiagnostics = true; } else { diagnosticsBag = diagnostics.DiagnosticBag; ownsDiagnostics = false; } MethodSymbol? baseOrThisInitializer = GetConstructorThisOrBaseSymbol(constructorBody); NullableWalker.AnalyzeIfNeeded( compilation, method, nodeToAnalyze, diagnosticsBag, useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: true, baseOrThisInitializer, out var afterInitializersState); if (ownsDiagnostics) { diagnosticsBag.Free(); } return afterInitializersState; } private static MethodSymbol? GetConstructorThisOrBaseSymbol(BoundNode? constructorBody) { return constructorBody is BoundConstructorMethodBody { Initializer: BoundExpressionStatement { Expression: BoundCall { Method: { MethodKind: MethodKind.Constructor } initializerMethod } } } ? initializerMethod : null; } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information. This method is only /// used when nullable is explicitly enabled for all methods but disabled otherwise to verify that /// correct semantic information is being recorded for all bound nodes. The results are thrown away. /// </summary> internal static void AnalyzeWithoutRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, DiagnosticBag diagnostics, bool createSnapshots) { _ = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState: GetAfterInitializersState(compilation, symbol, node), diagnostics, createSnapshots, requiresAnalysis: false); } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information, and returns an /// updated BoundNode with the information populated. /// </summary> internal static BoundNode AnalyzeAndRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, out SnapshotManager? snapshotManager, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> analyzedNullabilitiesMap; (snapshotManager, analyzedNullabilitiesMap) = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState, diagnostics, createSnapshots, requiresAnalysis: true); return Rewrite(analyzedNullabilitiesMap, snapshotManager, node, ref remappedSymbols); } private static (SnapshotManager?, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>) AnalyzeWithSemanticInfo( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, bool requiresAnalysis) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); // Attributes don't have a symbol, which is what SnapshotBuilder uses as an index for maintaining global state. // Until we have a workaround for this, disable snapshots for null symbols. // https://github.com/dotnet/roslyn/issues/36066 var snapshotBuilder = createSnapshots && symbol != null ? new SnapshotManager.Builder() : null; Analyze( compilation, symbol, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: true, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState, baseOrThisInitializer: null, analyzedNullabilities, snapshotBuilder, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); var snapshotManager = snapshotBuilder?.ToManagerAndFree(); #if DEBUG // https://github.com/dotnet/roslyn/issues/34993 Enable for all calls if (isNullableAnalysisEnabledAnywhere(compilation)) { DebugVerifier.Verify(analyzedNullabilitiesMap, snapshotManager, node); } static bool isNullableAnalysisEnabledAnywhere(CSharpCompilation compilation) { if (compilation.Options.NullableContextOptions != NullableContextOptions.Disable) { return true; } return compilation.SyntaxTrees.Any(static tree => ((CSharpSyntaxTree)tree).IsNullableAnalysisEnabled(new Text.TextSpan(0, tree.Length)) == true); } #endif return (snapshotManager, analyzedNullabilitiesMap); } internal static BoundNode AnalyzeAndRewriteSpeculation( int position, BoundNode node, Binder binder, SnapshotManager originalSnapshots, out SnapshotManager newSnapshots, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); var newSnapshotBuilder = new SnapshotManager.Builder(); var (variables, localState) = originalSnapshots.GetSnapshot(position); var symbol = variables.Symbol; var walker = new NullableWalker( binder.Compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, binder.Conversions, Variables.Create(variables), baseOrThisInitializer: null, returnTypesOpt: null, analyzedNullabilities, newSnapshotBuilder, isSpeculative: true); try { Analyze(walker, symbol, diagnostics: null, LocalState.Create(localState), snapshotBuilderOpt: newSnapshotBuilder); } finally { walker.Free(); } var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); newSnapshots = newSnapshotBuilder.ToManagerAndFree(); #if DEBUG DebugVerifier.Verify(analyzedNullabilitiesMap, newSnapshots, node); #endif return Rewrite(analyzedNullabilitiesMap, newSnapshots, node, ref remappedSymbols); } private static BoundNode Rewrite(ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> updatedNullabilities, SnapshotManager? snapshotManager, BoundNode node, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var remappedSymbolsBuilder = ImmutableDictionary.CreateBuilder<Symbol, Symbol>(Symbols.SymbolEqualityComparer.ConsiderEverything, Symbols.SymbolEqualityComparer.ConsiderEverything); if (remappedSymbols is object) { // When we're rewriting for the speculative model, there will be a set of originally-mapped symbols, and we need to // use them in addition to any symbols found during this pass of the walker. remappedSymbolsBuilder.AddRange(remappedSymbols); } var rewriter = new NullabilityRewriter(updatedNullabilities, snapshotManager, remappedSymbolsBuilder); var rewrittenNode = rewriter.Visit(node); remappedSymbols = remappedSymbolsBuilder.ToImmutable(); return rewrittenNode; } private static bool HasRequiredLanguageVersion(CSharpCompilation compilation) { return compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion(); } /// <summary> /// Returns true if the nullable analysis is needed for the region represented by <paramref name="syntaxNode"/>. /// The syntax node is used to determine the overall nullable context for the region. /// </summary> internal static bool NeedsAnalysis(CSharpCompilation compilation, SyntaxNode syntaxNode) { return HasRequiredLanguageVersion(compilation) && (compilation.IsNullableAnalysisEnabledIn(syntaxNode) || compilation.IsNullableAnalysisEnabledAlways); } /// <summary>Analyzes a node in a "one-off" context, such as for attributes or parameter default values.</summary> /// <remarks><paramref name="syntax"/> is the syntax span used to determine the overall nullable context.</remarks> internal static void AnalyzeIfNeeded( Binder binder, BoundNode node, SyntaxNode syntax, DiagnosticBag diagnostics) { bool requiresAnalysis = true; var compilation = binder.Compilation; if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(syntax)) { if (!compilation.IsNullableAnalysisEnabledAlways) { return; } diagnostics = new DiagnosticBag(); requiresAnalysis = false; } Analyze( compilation, symbol: null, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: null, baseOrThisInitializer: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); } internal static void Analyze( CSharpCompilation compilation, BoundLambda lambda, Conversions conversions, DiagnosticBag diagnostics, MethodSymbol? delegateInvokeMethodOpt, VariableState initialState, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt) { var symbol = lambda.Symbol; var variables = Variables.Create(initialState.Variables).CreateNestedMethodScope(symbol); UseDelegateInvokeParameterAndReturnTypes(lambda, delegateInvokeMethodOpt, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); var walker = new NullableWalker( compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: useDelegateInvokeParameterTypes, useDelegateInvokeReturnType: useDelegateInvokeReturnType, delegateInvokeMethodOpt: delegateInvokeMethodOpt, lambda.Body, lambda.Binder, conversions, variables, baseOrThisInitializer: null, returnTypesOpt, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); try { var localState = LocalState.Create(initialState.VariableNullableStates).CreateNestedMethodState(variables); Analyze(walker, symbol, diagnostics, localState, snapshotBuilderOpt: null); } finally { walker.Free(); } } private static void Analyze( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, Conversions conversions, DiagnosticBag diagnostics, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, VariableState? initialState, MethodSymbol? baseOrThisInitializer, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) { Debug.Assert(diagnostics != null); var walker = new NullableWalker(compilation, symbol, useConstructorExitWarnings, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType, delegateInvokeMethodOpt, node, binder, conversions, initialState is null ? null : Variables.Create(initialState.Variables), baseOrThisInitializer, returnTypesOpt, analyzedNullabilityMapOpt, snapshotBuilderOpt); finalNullableState = null; try { Analyze(walker, symbol, diagnostics, initialState is null ? (Optional<LocalState>)default : LocalState.Create(initialState.VariableNullableStates), snapshotBuilderOpt, requiresAnalysis); if (getFinalNullableState) { Debug.Assert(!walker.IsConditionalState); finalNullableState = GetVariableState(walker._variables, walker.State); } } finally { walker.Free(); } } private static void Analyze( NullableWalker walker, Symbol? symbol, DiagnosticBag? diagnostics, Optional<LocalState> initialState, SnapshotManager.Builder? snapshotBuilderOpt, bool requiresAnalysis = true) { Debug.Assert(snapshotBuilderOpt is null || symbol is object); var previousSlot = snapshotBuilderOpt?.EnterNewWalker(symbol!) ?? -1; try { bool badRegion = false; ImmutableArray<PendingBranch> returns = walker.Analyze(ref badRegion, initialState); diagnostics?.AddRange(walker.Diagnostics); Debug.Assert(!badRegion); } catch (CancelledByStackGuardException ex) when (diagnostics != null) { ex.AddAnError(diagnostics); } finally { snapshotBuilderOpt?.ExitWalker(walker.SaveSharedState(), previousSlot); } walker.RecordNullableAnalysisData(symbol, requiresAnalysis); } private void RecordNullableAnalysisData(Symbol? symbol, bool requiredAnalysis) { if (compilation.TestOnlyCompilationData is NullableAnalysisData { Data: { } state }) { var key = (object?)symbol ?? methodMainNode.Syntax; if (state.TryGetValue(key, out var result)) { Debug.Assert(result.RequiredAnalysis == requiredAnalysis); } else { state.TryAdd(key, new Data(_variables.GetTotalVariableCount(), requiredAnalysis)); } } } private SharedWalkerState SaveSharedState() { return new SharedWalkerState(_variables.CreateSnapshot()); } private void TakeIncrementalSnapshot(BoundNode? node) { Debug.Assert(!IsConditionalState); _snapshotBuilderOpt?.TakeIncrementalSnapshot(node, State); } private void SetUpdatedSymbol(BoundNode node, Symbol originalSymbol, Symbol updatedSymbol) { if (_snapshotBuilderOpt is null) { return; } var lambdaIsExactMatch = false; if (node is BoundLambda boundLambda && originalSymbol is LambdaSymbol l && updatedSymbol is NamedTypeSymbol n) { if (!AreLambdaAndNewDelegateSimilar(l, n)) { return; } lambdaIsExactMatch = updatedSymbol.Equals(boundLambda.Type!.GetDelegateType(), TypeCompareKind.ConsiderEverything); } #if DEBUG Debug.Assert(node is object); Debug.Assert(AreCloseEnough(originalSymbol, updatedSymbol), $"Attempting to set {node.Syntax} from {originalSymbol.ToDisplayString()} to {updatedSymbol.ToDisplayString()}"); #endif if (lambdaIsExactMatch || Symbol.Equals(originalSymbol, updatedSymbol, TypeCompareKind.ConsiderEverything)) { // If the symbol is reset, remove the updated symbol so we don't needlessly update the // bound node later on. We do this unconditionally, as Remove will just return false // if the key wasn't in the dictionary. _snapshotBuilderOpt.RemoveSymbolIfPresent(node, originalSymbol); } else { _snapshotBuilderOpt.SetUpdatedSymbol(node, originalSymbol, updatedSymbol); } } protected override void Normalize(ref LocalState state) { if (!state.Reachable) return; state.Normalize(this, _variables); } private NullableFlowState GetDefaultState(ref LocalState state, int slot) { Debug.Assert(slot > 0); if (!state.Reachable) return NullableFlowState.NotNull; var variable = _variables[slot]; var symbol = variable.Symbol; switch (symbol.Kind) { case SymbolKind.Local: { var local = (LocalSymbol)symbol; if (!_variables.TryGetType(local, out TypeWithAnnotations localType)) { localType = local.TypeWithAnnotations; } return localType.ToTypeWithState().State; } case SymbolKind.Parameter: { var parameter = (ParameterSymbol)symbol; if (!_variables.TryGetType(parameter, out TypeWithAnnotations parameterType)) { parameterType = parameter.TypeWithAnnotations; } return GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; } case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: return GetDefaultState(symbol); case SymbolKind.ErrorType: return NullableFlowState.NotNull; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } protected override bool TryGetReceiverAndMember(BoundExpression expr, out BoundExpression? receiver, [NotNullWhen(true)] out Symbol? member) { receiver = null; member = null; switch (expr.Kind) { case BoundKind.FieldAccess: { var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; member = fieldSymbol; if (fieldSymbol.IsFixedSizeBuffer) { return false; } if (fieldSymbol.IsStatic) { return true; } receiver = fieldAccess.ReceiverOpt; break; } case BoundKind.EventAccess: { var eventAccess = (BoundEventAccess)expr; var eventSymbol = eventAccess.EventSymbol; // https://github.com/dotnet/roslyn/issues/29901 Use AssociatedField for field-like events? member = eventSymbol; if (eventSymbol.IsStatic) { return true; } receiver = eventAccess.ReceiverOpt; break; } case BoundKind.PropertyAccess: { var propAccess = (BoundPropertyAccess)expr; var propSymbol = propAccess.PropertySymbol; member = propSymbol; if (propSymbol.IsStatic) { return true; } receiver = propAccess.ReceiverOpt; break; } } Debug.Assert(member?.RequiresInstanceReceiver() ?? true); return member is object && receiver is object && receiver.Kind != BoundKind.TypeExpression && receiver.Type is object; } protected override int MakeSlot(BoundExpression node) { int result = makeSlot(node); #if DEBUG if (result != -1) { // Check that the slot represents a value of an equivalent type to the node TypeSymbol slotType = NominalSlotType(result); TypeSymbol? nodeType = node.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = this.compilation.Conversions; Debug.Assert(node.HasErrors || (nodeType is { } && (nodeType.IsErrorType() || conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(slotType, nodeType, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(slotType, nodeType, ref discardedUseSiteInfo)))); } #endif return result; int makeSlot(BoundExpression node) { switch (node.Kind) { case BoundKind.ThisReference: case BoundKind.BaseReference: { var method = getTopLevelMethod(_symbol as MethodSymbol); var thisParameter = method?.ThisParameter; return thisParameter is object ? GetOrCreateSlot(thisParameter) : -1; } case BoundKind.Conversion: { int slot = getPlaceholderSlot(node); if (slot > 0) { return slot; } var conv = (BoundConversion)node; switch (conv.Conversion.Kind) { case ConversionKind.ExplicitNullable: { var operand = conv.Operand; var operandType = operand.Type; var convertedType = conv.Type; if (AreNullableAndUnderlyingTypes(operandType, convertedType, out _)) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. // For instance, in the following, when evaluating `((A)a).B` we need to recognize // the nullability of `(A)a` (not nullable) and the slot (the slot for `a.Value`). // struct A { B? B; } // struct B { } // if (a?.B != null) _ = ((A)a).B.Value; // no warning int containingSlot = MakeSlot(operand); return containingSlot < 0 ? -1 : GetNullableOfTValueSlot(operandType, containingSlot, out _); } } break; case ConversionKind.ConditionalExpression or ConversionKind.SwitchExpression or ConversionKind.ObjectCreation when IsTargetTypedExpression(conv.Operand) && TypeSymbol.Equals(conv.Type, conv.Operand.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes): case ConversionKind.Identity: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.Boxing: // No need to create a slot for the boxed value (in the Boxing case) since assignment already // clones slots and there is not another scenario where creating a slot is observable. return MakeSlot(conv.Operand); } } break; case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.ObjectCreationExpression: case BoundKind.DynamicObjectCreationExpression: case BoundKind.AnonymousObjectCreationExpression: case BoundKind.NewT: case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return getPlaceholderSlot(node); case BoundKind.ConditionalAccess: return getPlaceholderSlot(node); case BoundKind.ConditionalReceiver: return _lastConditionalAccessSlot; default: { int slot = getPlaceholderSlot(node); return (slot > 0) ? slot : base.MakeSlot(node); } } return -1; } int getPlaceholderSlot(BoundExpression expr) { if (_placeholderLocalsOpt != null && _placeholderLocalsOpt.TryGetValue(expr, out var placeholder)) { return GetOrCreateSlot(placeholder); } return -1; } static MethodSymbol? getTopLevelMethod(MethodSymbol? method) { while (method is object) { var container = method.ContainingSymbol; if (container.Kind == SymbolKind.NamedType) { return method; } method = container as MethodSymbol; } return null; } } protected override int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bool forceSlotEvenIfEmpty = false, bool createIfMissing = true) { if (containingSlot > 0 && !IsSlotMember(containingSlot, symbol)) return -1; return base.GetOrCreateSlot(symbol, containingSlot, forceSlotEvenIfEmpty, createIfMissing); } private void VisitAndUnsplitAll<T>(ImmutableArray<T> nodes) where T : BoundNode { if (nodes.IsDefault) { return; } foreach (var node in nodes) { Visit(node); Unsplit(); } } private void VisitWithoutDiagnostics(BoundNode? node) { var previousDiagnostics = _disableDiagnostics; _disableDiagnostics = true; Visit(node); _disableDiagnostics = previousDiagnostics; } protected override void VisitRvalue(BoundExpression? node, bool isKnownToBeAnLvalue = false) { Visit(node); VisitRvalueEpilogue(node); } /// <summary> /// The contents of this method, particularly <see cref="UseRvalueOnly"/>, are problematic when /// inlined. The methods themselves are small but they end up allocating significantly larger /// frames due to the use of biggish value types within them. The <see cref="VisitRvalue"/> method /// is used on a hot path for fluent calls and this size change is enough that it causes us /// to exceed our thresholds in EndToEndTests.OverflowOnFluentCall. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private void VisitRvalueEpilogue(BoundExpression? node) { Unsplit(); UseRvalueOnly(node); // drop lvalue part } private TypeWithState VisitRvalueWithState(BoundExpression? node) { VisitRvalue(node); return ResultType; } private TypeWithAnnotations VisitLvalueWithAnnotations(BoundExpression node) { VisitLValue(node); Unsplit(); return LvalueResultType; } private static object GetTypeAsDiagnosticArgument(TypeSymbol? typeOpt) { return typeOpt ?? (object)"<null>"; } private static object GetParameterAsDiagnosticArgument(ParameterSymbol? parameterOpt) { return parameterOpt is null ? (object)"" : new FormattedSymbol(parameterOpt, SymbolDisplayFormat.ShortFormat); } private static object GetContainingSymbolAsDiagnosticArgument(ParameterSymbol? parameterOpt) { var containingSymbol = parameterOpt?.ContainingSymbol; return containingSymbol is null ? (object)"" : new FormattedSymbol(containingSymbol, SymbolDisplayFormat.MinimallyQualifiedFormat); } private enum AssignmentKind { Assignment, Return, Argument, ForEachIterationVariable } /// <summary> /// Should we warn for assigning this state into this type? /// /// This should often be checked together with <seealso cref="IsDisallowedNullAssignment(TypeWithState, FlowAnalysisAnnotations)"/> /// It catches putting a `null` into a `[DisallowNull]int?` for example, which cannot simply be represented as a non-nullable target type. /// </summary> private static bool ShouldReportNullableAssignment(TypeWithAnnotations type, NullableFlowState state) { if (!type.HasType || type.Type.IsValueType) { return false; } switch (type.NullableAnnotation) { case NullableAnnotation.Oblivious: case NullableAnnotation.Annotated: return false; } switch (state) { case NullableFlowState.NotNull: return false; case NullableFlowState.MaybeNull: if (type.Type.IsTypeParameterDisallowingAnnotationInCSharp8() && !(type.Type is TypeParameterSymbol { IsNotNullable: true })) { return false; } break; } return true; } /// <summary> /// Reports top-level nullability problem in assignment. /// Any conversion of the value should have been applied. /// </summary> private void ReportNullableAssignmentIfNecessary( BoundExpression? value, TypeWithAnnotations targetType, TypeWithState valueType, bool useLegacyWarnings, AssignmentKind assignmentKind = AssignmentKind.Assignment, ParameterSymbol? parameterOpt = null, Location? location = null) { // Callers should apply any conversions before calling this method // (see https://github.com/dotnet/roslyn/issues/39867). if (targetType.HasType && !targetType.Type.Equals(valueType.Type, TypeCompareKind.AllIgnoreOptions)) { return; } if (value == null || // This prevents us from giving undesired warnings for synthesized arguments for optional parameters, // but allows us to give warnings for synthesized assignments to record properties and for parameter default values at the declaration site. // Interpolated string handler argument placeholders _are_ compiler generated, but the user should be warned about them anyway. (value.WasCompilerGenerated && assignmentKind == AssignmentKind.Argument && value.Kind != BoundKind.InterpolatedStringArgumentPlaceholder) || !ShouldReportNullableAssignment(targetType, valueType.State)) { return; } location ??= value.Syntax.GetLocation(); var unwrappedValue = SkipReferenceConversions(value); if (unwrappedValue.IsSuppressed) { return; } if (value.ConstantValue?.IsNull == true && !useLegacyWarnings) { // Report warning converting null literal to non-nullable reference type. // target (e.g.: `object F() => null;` or calling `void F(object y)` with `F(null)`). ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullAsNonNullable, location); } else if (assignmentKind == AssignmentKind.Argument) { ReportDiagnostic(ErrorCode.WRN_NullReferenceArgument, location, GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); LearnFromNonNullTest(value, ref State); } else if (useLegacyWarnings) { if (isMaybeDefaultValue(valueType) && !allowUnconstrainedTypeParameterAnnotations(compilation)) { // No W warning reported assigning or casting [MaybeNull]T value to T // because there is no syntax for declaring the target type as [MaybeNull]T. return; } ReportNonSafetyDiagnostic(location); } else { ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullReferenceAssignment, location); } static bool isMaybeDefaultValue(TypeWithState valueType) { return valueType.Type?.TypeKind == TypeKind.TypeParameter && valueType.State == NullableFlowState.MaybeDefault; } static bool allowUnconstrainedTypeParameterAnnotations(CSharpCompilation compilation) { // Check IDS_FeatureDefaultTypeParameterConstraint feature since `T?` and `where ... : default` // are treated as a single feature, even though the errors reported for the two cases are distinct. var requiredVersion = MessageID.IDS_FeatureDefaultTypeParameterConstraint.RequiredVersion(); return requiredVersion <= compilation.LanguageVersion; } } internal static bool AreParameterAnnotationsCompatible( RefKind refKind, TypeWithAnnotations overriddenType, FlowAnalysisAnnotations overriddenAnnotations, TypeWithAnnotations overridingType, FlowAnalysisAnnotations overridingAnnotations, bool forRef = false) { // We've already checked types and annotations, let's check nullability attributes as well // Return value is treated as an `out` parameter (or `ref` if it is a `ref` return) if (refKind == RefKind.Ref) { // ref variables are invariant return AreParameterAnnotationsCompatible(RefKind.None, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations, forRef: true) && AreParameterAnnotationsCompatible(RefKind.Out, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations); } if (refKind == RefKind.None || refKind == RefKind.In) { // pre-condition attributes // Check whether we can assign a value from overridden parameter to overriding var valueState = GetParameterState( overriddenType, overriddenAnnotations); if (isBadAssignment(valueState, overridingType, overridingAnnotations)) { return false; } // unconditional post-condition attributes on inputs bool overridingHasNotNull = (overridingAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; bool overriddenHasNotNull = (overriddenAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; if (overriddenHasNotNull && !overridingHasNotNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise not to return if parameter is null) return false; } bool overridingHasMaybeNull = (overridingAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; bool overriddenHasMaybeNull = (overriddenAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; if (overriddenHasMaybeNull && !overridingHasMaybeNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise to only return if parameter is null) return false; } } if (refKind == RefKind.Out) { // post-condition attributes (`Maybe/NotNull` and `Maybe/NotNullWhen`) if (!canAssignOutputValueWhen(true) || !canAssignOutputValueWhen(false)) { return false; } } return true; bool canAssignOutputValueWhen(bool sense) { var valueWhen = ApplyUnconditionalAnnotations( overridingType.ToTypeWithState(), makeUnconditionalAnnotation(overridingAnnotations, sense)); var destAnnotationsWhen = ToInwardAnnotations(makeUnconditionalAnnotation(overriddenAnnotations, sense)); if (isBadAssignment(valueWhen, overriddenType, destAnnotationsWhen)) { // Can't assign value from overriding to overridden in 'sense' case return false; } return true; } static bool isBadAssignment(TypeWithState valueState, TypeWithAnnotations destinationType, FlowAnalysisAnnotations destinationAnnotations) { if (ShouldReportNullableAssignment( ApplyLValueAnnotations(destinationType, destinationAnnotations), valueState.State)) { return true; } if (IsDisallowedNullAssignment(valueState, destinationAnnotations)) { return true; } return false; } // Convert both conditional annotations to unconditional ones or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotation(FlowAnalysisAnnotations annotations, bool sense) { if (sense) { var unconditionalAnnotationWhenTrue = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenTrue, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenTrue, FlowAnalysisAnnotations.MaybeNullWhenTrue, FlowAnalysisAnnotations.MaybeNull); } var unconditionalAnnotationWhenFalse = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenFalse, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenFalse, FlowAnalysisAnnotations.MaybeNullWhenFalse, FlowAnalysisAnnotations.MaybeNull); } // Convert Maybe/NotNullWhen into Maybe/NotNull or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotationCore(FlowAnalysisAnnotations annotations, FlowAnalysisAnnotations conditionalAnnotation, FlowAnalysisAnnotations replacementAnnotation) { if ((annotations & conditionalAnnotation) != 0) { return annotations | replacementAnnotation; } return annotations & ~replacementAnnotation; } } private static bool IsDefaultValue(BoundExpression expr) { switch (expr.Kind) { case BoundKind.Conversion: { var conversion = (BoundConversion)expr; var conversionKind = conversion.Conversion.Kind; return (conversionKind == ConversionKind.DefaultLiteral || conversionKind == ConversionKind.NullLiteral) && IsDefaultValue(conversion.Operand); } case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: return true; default: return false; } } private void ReportNullabilityMismatchInAssignment(SyntaxNode syntaxNode, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, syntaxNode, sourceType, destinationType); } private void ReportNullabilityMismatchInAssignment(Location location, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, location, sourceType, destinationType); } /// <summary> /// Update tracked value on assignment. /// </summary> private void TrackNullableStateForAssignment( BoundExpression? valueOpt, TypeWithAnnotations targetType, int targetSlot, TypeWithState valueType, int valueSlot = -1) { Debug.Assert(!IsConditionalState); if (this.State.Reachable) { if (!targetType.HasType) { return; } if (targetSlot <= 0 || targetSlot == valueSlot) { return; } if (!this.State.HasValue(targetSlot)) Normalize(ref this.State); var newState = valueType.State; SetStateAndTrackForFinally(ref this.State, targetSlot, newState); InheritDefaultState(targetType.Type, targetSlot); // https://github.com/dotnet/roslyn/issues/33428: Can the areEquivalentTypes check be removed // if InheritNullableStateOfMember asserts the member is valid for target and value? if (areEquivalentTypes(targetType, valueType)) { if (targetType.Type.IsReferenceType || targetType.TypeKind == TypeKind.TypeParameter || targetType.IsNullableType()) { if (valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot: targetSlot); } } else if (EmptyStructTypeCache.IsTrackableStructType(targetType.Type)) { InheritNullableStateOfTrackableStruct(targetType.Type, targetSlot, valueSlot, isDefaultValue: !(valueOpt is null) && IsDefaultValue(valueOpt), skipSlot: targetSlot); } } } static bool areEquivalentTypes(TypeWithAnnotations target, TypeWithState assignedValue) => target.Type.Equals(assignedValue.Type, TypeCompareKind.AllIgnoreOptions); } private void ReportNonSafetyDiagnostic(Location location) { ReportDiagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, location); } private void ReportDiagnostic(ErrorCode errorCode, SyntaxNode syntaxNode, params object[] arguments) { ReportDiagnostic(errorCode, syntaxNode.GetLocation(), arguments); } private void ReportDiagnostic(ErrorCode errorCode, Location location, params object[] arguments) { Debug.Assert(ErrorFacts.NullableWarnings.Contains(MessageProvider.Instance.GetIdForErrorCode((int)errorCode))); if (IsReachable() && !_disableDiagnostics) { Diagnostics.Add(errorCode, location, arguments); } } private void InheritNullableStateOfTrackableStruct(TypeSymbol targetType, int targetSlot, int valueSlot, bool isDefaultValue, int skipSlot = -1) { Debug.Assert(targetSlot > 0); Debug.Assert(EmptyStructTypeCache.IsTrackableStructType(targetType)); if (skipSlot < 0) { skipSlot = targetSlot; } if (!isDefaultValue && valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot); } else { foreach (var field in _emptyStructTypeCache.GetStructInstanceFields(targetType)) { InheritNullableStateOfMember(targetSlot, valueSlot, field, isDefaultValue: isDefaultValue, skipSlot); } } } private bool IsSlotMember(int slot, Symbol possibleMember) { TypeSymbol possibleBase = possibleMember.ContainingType; TypeSymbol possibleDerived = NominalSlotType(slot); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = _conversions.WithNullability(false); return conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo); } // 'skipSlot' is the original target slot that should be skipped in case of cycles. private void InheritNullableStateOfMember(int targetContainerSlot, int valueContainerSlot, Symbol member, bool isDefaultValue, int skipSlot) { Debug.Assert(targetContainerSlot > 0); Debug.Assert(skipSlot > 0); // Ensure member is valid for target and value. if (!IsSlotMember(targetContainerSlot, member)) return; TypeWithAnnotations fieldOrPropertyType = member.GetTypeOrReturnType(); if (fieldOrPropertyType.Type.IsReferenceType || fieldOrPropertyType.TypeKind == TypeKind.TypeParameter || fieldOrPropertyType.IsNullableType()) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { NullableFlowState value = isDefaultValue ? NullableFlowState.MaybeNull : fieldOrPropertyType.ToTypeWithState().State; int valueMemberSlot = -1; if (valueContainerSlot > 0) { valueMemberSlot = VariableSlot(member, valueContainerSlot); if (valueMemberSlot == skipSlot) { return; } value = this.State.HasValue(valueMemberSlot) ? this.State[valueMemberSlot] : NullableFlowState.NotNull; } SetStateAndTrackForFinally(ref this.State, targetMemberSlot, value); if (valueMemberSlot > 0) { InheritNullableStateOfTrackableType(targetMemberSlot, valueMemberSlot, skipSlot); } } } else if (EmptyStructTypeCache.IsTrackableStructType(fieldOrPropertyType.Type)) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { int valueMemberSlot = (valueContainerSlot > 0) ? GetOrCreateSlot(member, valueContainerSlot) : -1; if (valueMemberSlot == skipSlot) { return; } InheritNullableStateOfTrackableStruct(fieldOrPropertyType.Type, targetMemberSlot, valueMemberSlot, isDefaultValue: isDefaultValue, skipSlot); } } } private TypeSymbol NominalSlotType(int slot) { return _variables[slot].Symbol.GetTypeOrReturnType().Type; } /// <summary> /// Whenever assigning a variable, and that variable is not declared at the point the state is being set, /// and the new state is not <see cref="NullableFlowState.NotNull"/>, this method should be called to perform the /// state setting and to ensure the mutation is visible outside the finally block when the mutation occurs in a /// finally block. /// </summary> private void SetStateAndTrackForFinally(ref LocalState state, int slot, NullableFlowState newState) { state[slot] = newState; if (newState != NullableFlowState.NotNull && NonMonotonicState.HasValue) { var tryState = NonMonotonicState.Value; if (tryState.HasVariable(slot)) { tryState[slot] = newState.Join(tryState[slot]); NonMonotonicState = tryState; } } } protected override void JoinTryBlockState(ref LocalState self, ref LocalState other) { var tryState = other.GetStateForVariables(self.Id); Join(ref self, ref tryState); } private void InheritDefaultState(TypeSymbol targetType, int targetSlot) { Debug.Assert(targetSlot > 0); // Reset the state of any members of the target. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, targetSlot); foreach (var (variable, slot) in members) { var symbol = AsMemberOfType(targetType, variable.Symbol); SetStateAndTrackForFinally(ref this.State, slot, GetDefaultState(symbol)); InheritDefaultState(symbol.GetTypeOrReturnType().Type, slot); } members.Free(); } private NullableFlowState GetDefaultState(Symbol symbol) => ApplyUnconditionalAnnotations(symbol.GetTypeOrReturnType().ToTypeWithState(), GetRValueAnnotations(symbol)).State; private void InheritNullableStateOfTrackableType(int targetSlot, int valueSlot, int skipSlot) { Debug.Assert(targetSlot > 0); Debug.Assert(valueSlot > 0); // Clone the state for members that have been set on the value. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, valueSlot); foreach (var (variable, slot) in members) { var member = variable.Symbol; Debug.Assert(member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property || member.Kind == SymbolKind.Event); InheritNullableStateOfMember(targetSlot, valueSlot, member, isDefaultValue: false, skipSlot); } members.Free(); } protected override LocalState TopState() { var state = LocalState.ReachableState(_variables); state.PopulateAll(this); return state; } protected override LocalState UnreachableState() { return LocalState.UnreachableState(_variables); } protected override LocalState ReachableBottomState() { // Create a reachable state in which all variables are known to be non-null. return LocalState.ReachableState(_variables); } private void EnterParameters() { if (!(CurrentSymbol is MethodSymbol methodSymbol)) { return; } if (methodSymbol is SynthesizedRecordConstructor) { if (_hasInitialState) { // A record primary constructor's parameters are entered before analyzing initializers. // On the second pass, the correct parameter states (potentially modified by initializers) // are contained in the initial state. return; } } else if (methodSymbol.IsConstructor()) { if (!_hasInitialState) { // For most constructors, we only enter parameters after analyzing initializers. return; } } // The partial definition part may include optional parameters whose default values we want to simulate assigning at the beginning of the method methodSymbol = methodSymbol.PartialDefinitionPart ?? methodSymbol; var methodParameters = methodSymbol.Parameters; var signatureParameters = (_useDelegateInvokeParameterTypes ? _delegateInvokeMethod! : methodSymbol).Parameters; // save a state representing the possibility that parameter default values were not assigned to the parameters. var parameterDefaultsNotAssignedState = State.Clone(); for (int i = 0; i < methodParameters.Length; i++) { var parameter = methodParameters[i]; // In error scenarios, the method can potentially have more parameters than the signature. If so, use the parameter type for those // errored parameters var parameterType = i >= signatureParameters.Length ? parameter.TypeWithAnnotations : signatureParameters[i].TypeWithAnnotations; EnterParameter(parameter, parameterType); } Join(ref State, ref parameterDefaultsNotAssignedState); } private void EnterParameter(ParameterSymbol parameter, TypeWithAnnotations parameterType) { _variables.SetType(parameter, parameterType); if (parameter.RefKind != RefKind.Out) { int slot = GetOrCreateSlot(parameter); Debug.Assert(!IsConditionalState); if (slot > 0) { var state = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; this.State[slot] = state; if (EmptyStructTypeCache.IsTrackableStructType(parameterType.Type)) { InheritNullableStateOfTrackableStruct( parameterType.Type, slot, valueSlot: -1, isDefaultValue: parameter.ExplicitDefaultConstantValue?.IsNull == true); } } } } public override BoundNode? VisitParameterEqualsValue(BoundParameterEqualsValue equalsValue) { var parameter = equalsValue.Parameter; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterLValueType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); var resultType = VisitOptionalImplicitConversion( equalsValue.Value, parameterLValueType, useLegacyWarnings: false, trackMembers: false, assignmentKind: AssignmentKind.Assignment); Unsplit(); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, equalsValue.Value.Syntax.Location); return null; } internal static TypeWithState GetParameterState(TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) { if ((parameterAnnotations & FlowAnalysisAnnotations.AllowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.MaybeDefault); } if ((parameterAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.NotNull); } return parameterType.ToTypeWithState(); } public sealed override BoundNode? VisitReturnStatement(BoundReturnStatement node) { Debug.Assert(!IsConditionalState); var expr = node.ExpressionOpt; if (expr == null) { EnforceDoesNotReturn(node.Syntax); PendingBranches.Add(new PendingBranch(node, this.State, label: null)); SetUnreachable(); return null; } // Should not convert to method return type when inferring return type (when _returnTypesOpt != null). if (_returnTypesOpt == null && TryGetReturnType(out TypeWithAnnotations returnType, out FlowAnalysisAnnotations returnAnnotations)) { if (node.RefKind == RefKind.None && returnType.Type.SpecialType == SpecialType.System_Boolean) { // visit the expression without unsplitting, then check parameters marked with flow analysis attributes Visit(expr); } else { TypeWithState returnState; if (node.RefKind == RefKind.None) { returnState = VisitOptionalImplicitConversion(expr, returnType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); } else { // return ref expr; returnState = VisitRefExpression(expr, returnType); } // If the return has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(returnState, ToInwardAnnotations(returnAnnotations), node.Syntax.Location, boundValueOpt: expr); } } else { var result = VisitRvalueWithState(expr); if (_returnTypesOpt != null) { _returnTypesOpt.Add((node, result.ToTypeWithAnnotations(compilation))); } } EnforceDoesNotReturn(node.Syntax); if (IsConditionalState) { var joinedState = this.StateWhenTrue.Clone(); Join(ref joinedState, ref this.StateWhenFalse); PendingBranches.Add(new PendingBranch(node, joinedState, label: null, this.IsConditionalState, this.StateWhenTrue, this.StateWhenFalse)); } else { PendingBranches.Add(new PendingBranch(node, this.State, label: null)); } Unsplit(); if (CurrentSymbol is MethodSymbol method) { EnforceNotNullIfNotNull(node.Syntax, this.State, method.Parameters, method.ReturnNotNullIfParameterNotNull, ResultType.State, outputParam: null); } SetUnreachable(); return null; } private TypeWithState VisitRefExpression(BoundExpression expr, TypeWithAnnotations destinationType) { Visit(expr); TypeWithState resultType = ResultType; if (!expr.IsSuppressed && RemoveConversion(expr, includeExplicitConversions: false).expression.Kind != BoundKind.ThrowExpression) { var lvalueResultType = LvalueResultType; if (IsNullabilityMismatch(lvalueResultType, destinationType)) { // declared types must match ReportNullabilityMismatchInAssignment(expr.Syntax, lvalueResultType, destinationType); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(expr, destinationType, resultType, useLegacyWarnings: false); } } return resultType; } private bool TryGetReturnType(out TypeWithAnnotations type, out FlowAnalysisAnnotations annotations) { var method = CurrentSymbol as MethodSymbol; if (method is null) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } var delegateOrMethod = _useDelegateInvokeReturnType ? _delegateInvokeMethod! : method; var returnType = delegateOrMethod.ReturnTypeWithAnnotations; Debug.Assert((object)returnType != LambdaSymbol.ReturnTypeIsBeingInferred); if (returnType.IsVoidType()) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } if (!method.IsAsync) { annotations = method.ReturnTypeFlowAnalysisAnnotations; type = ApplyUnconditionalAnnotations(returnType, annotations); return true; } if (method.IsAsyncEffectivelyReturningGenericTask(compilation)) { type = ((NamedTypeSymbol)returnType.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); annotations = FlowAnalysisAnnotations.None; return true; } type = default; annotations = FlowAnalysisAnnotations.None; return false; } public override BoundNode? VisitLocal(BoundLocal node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); var type = GetDeclaredLocalResult(local); if (!node.Type.Equals(type.Type, TypeCompareKind.ConsiderEverything | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames)) { // When the local is used before or during initialization, there can potentially be a mismatch between node.LocalSymbol.Type and node.Type. We // need to prefer node.Type as we shouldn't be changing the type of the BoundLocal node during rewrite. // https://github.com/dotnet/roslyn/issues/34158 Debug.Assert(node.Type.IsErrorType() || type.Type.IsErrorType()); type = TypeWithAnnotations.Create(node.Type, type.NullableAnnotation); } SetResult(node, GetAdjustedResult(type.ToTypeWithState(), slot), type); SplitIfBooleanConstant(node); return null; } public override BoundNode? VisitBlock(BoundBlock node) { DeclareLocals(node.Locals); VisitStatementsWithLocalFunctions(node); return null; } private void VisitStatementsWithLocalFunctions(BoundBlock block) { // Since the nullable flow state affects type information, and types can be queried by // the semantic model, there needs to be a single flow state input to a local function // that cannot be path-dependent. To decide the local starting state we Meet the state // of captured variables from all the uses of the local function, computing the // conservative combination of all potential starting states. // // For performance we split the analysis into two phases: the first phase where we // analyze everything except the local functions, hoping to visit all of the uses of the // local function, and then a pass where we visit the local functions. If there's no // recursion or calls between the local functions, the starting state of the local // function should be stable and we don't need a second pass. if (!TrackingRegions && !block.LocalFunctions.IsDefaultOrEmpty) { // First visit everything else foreach (var stmt in block.Statements) { if (stmt.Kind != BoundKind.LocalFunctionStatement) { VisitStatement(stmt); } } // Now visit the local function bodies foreach (var stmt in block.Statements) { if (stmt is BoundLocalFunctionStatement localFunc) { VisitLocalFunctionStatement(localFunc); } } } else { foreach (var stmt in block.Statements) { VisitStatement(stmt); } } } public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { var localFunc = node.Symbol; var localFunctionState = GetOrCreateLocalFuncUsages(localFunc); // The starting state is the top state, but with captured // variables set according to Joining the state at all the // local function use sites var state = TopState(); var startingState = localFunctionState.StartingState; startingState.ForEach( (slot, variables) => { var symbol = variables[variables.RootSlot(slot)].Symbol; if (Symbol.IsCaptured(symbol, localFunc)) { state[slot] = startingState[slot]; } }, _variables); localFunctionState.Visited = true; AnalyzeLocalFunctionOrLambda( node, localFunc, state, delegateInvokeMethod: null, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false); SetInvalidResult(); return null; } private Variables GetOrCreateNestedFunctionVariables(Variables container, MethodSymbol lambdaOrLocalFunction) { _nestedFunctionVariables ??= PooledDictionary<MethodSymbol, Variables>.GetInstance(); if (!_nestedFunctionVariables.TryGetValue(lambdaOrLocalFunction, out var variables)) { variables = container.CreateNestedMethodScope(lambdaOrLocalFunction); _nestedFunctionVariables.Add(lambdaOrLocalFunction, variables); } Debug.Assert((object?)variables.Container == container); return variables; } private void AnalyzeLocalFunctionOrLambda( IBoundLambdaOrFunction lambdaOrFunction, MethodSymbol lambdaOrFunctionSymbol, LocalState state, MethodSymbol? delegateInvokeMethod, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethod is object); Debug.Assert(!useDelegateInvokeReturnType || delegateInvokeMethod is object); var oldSymbol = this._symbol; this._symbol = lambdaOrFunctionSymbol; var oldCurrentSymbol = this.CurrentSymbol; this.CurrentSymbol = lambdaOrFunctionSymbol; var oldDelegateInvokeMethod = _delegateInvokeMethod; _delegateInvokeMethod = delegateInvokeMethod; var oldUseDelegateInvokeParameterTypes = _useDelegateInvokeParameterTypes; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; var oldUseDelegateInvokeReturnType = _useDelegateInvokeReturnType; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; var oldReturnTypes = _returnTypesOpt; _returnTypesOpt = null; #if DEBUG var oldCompletingTargetTypedExpression = _completingTargetTypedExpression; _completingTargetTypedExpression = false; #endif var oldState = this.State; _variables = GetOrCreateNestedFunctionVariables(_variables, lambdaOrFunctionSymbol); this.State = state.CreateNestedMethodState(_variables); var previousSlot = _snapshotBuilderOpt?.EnterNewWalker(lambdaOrFunctionSymbol) ?? -1; try { var oldPending = SavePending(); EnterParameters(); var oldPending2 = SavePending(); // If this is an iterator, there's an implicit branch before the first statement // of the function where the enumerable is returned. if (lambdaOrFunctionSymbol.IsIterator) { PendingBranches.Add(new PendingBranch(null, this.State, null)); } VisitAlways(lambdaOrFunction.Body); EnforceDoesNotReturn(syntaxOpt: null); EnforceParameterNotNullOnExit(null, this.State); RestorePending(oldPending2); // process any forward branches within the lambda body ImmutableArray<PendingBranch> pendingReturns = RemoveReturns(); foreach (var pendingReturn in pendingReturns) { if (pendingReturn.Branch is BoundReturnStatement returnStatement) { EnforceParameterNotNullOnExit(returnStatement.Syntax, pendingReturn.State); EnforceNotNullWhenForPendingReturn(pendingReturn, returnStatement); } } RestorePending(oldPending); } finally { _snapshotBuilderOpt?.ExitWalker(this.SaveSharedState(), previousSlot); } _variables = _variables.Container!; this.State = oldState; #if DEBUG _completingTargetTypedExpression = oldCompletingTargetTypedExpression; #endif _returnTypesOpt = oldReturnTypes; _useDelegateInvokeReturnType = oldUseDelegateInvokeReturnType; _useDelegateInvokeParameterTypes = oldUseDelegateInvokeParameterTypes; _delegateInvokeMethod = oldDelegateInvokeMethod; this.CurrentSymbol = oldCurrentSymbol; this._symbol = oldSymbol; } protected override void VisitLocalFunctionUse( LocalFunctionSymbol symbol, LocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) { // Do not use this overload in NullableWalker. Use the overload below instead. throw ExceptionUtilities.Unreachable; } private void VisitLocalFunctionUse(LocalFunctionSymbol symbol) { Debug.Assert(!IsConditionalState); var localFunctionState = GetOrCreateLocalFuncUsages(symbol); var state = State.GetStateForVariables(localFunctionState.StartingState.Id); if (Join(ref localFunctionState.StartingState, ref state) && localFunctionState.Visited) { // If the starting state of the local function has changed and we've already visited // the local function, we need another pass stateChangedAfterUse = true; } } public override BoundNode? VisitDoStatement(BoundDoStatement node) { DeclareLocals(node.Locals); return base.VisitDoStatement(node); } public override BoundNode? VisitWhileStatement(BoundWhileStatement node) { DeclareLocals(node.Locals); return base.VisitWhileStatement(node); } public override BoundNode? VisitWithExpression(BoundWithExpression withExpr) { Debug.Assert(!IsConditionalState); var receiver = withExpr.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); var resultType = ResultType.ToTypeWithAnnotations(compilation); var resultState = ApplyUnconditionalAnnotations(resultType.ToTypeWithState(), GetRValueAnnotations(withExpr.CloneMethod)); var resultSlot = GetOrCreatePlaceholderSlot(withExpr); // carry over the null state of members of 'receiver' to the result of the with-expression. TrackNullableStateForAssignment(receiver, resultType, resultSlot, resultState, MakeSlot(receiver)); // use the declared nullability of Clone() for the top-level nullability of the result of the with-expression. SetResult(withExpr, resultState, resultType); VisitObjectCreationInitializer(resultSlot, resultType.Type, withExpr.InitializerExpression, delayCompletionForType: false); // Note: this does not account for the scenario where `Clone()` returns maybe-null and the with-expression has no initializers. // Tracking in https://github.com/dotnet/roslyn/issues/44759 return null; } public override BoundNode? VisitForStatement(BoundForStatement node) { DeclareLocals(node.OuterLocals); DeclareLocals(node.InnerLocals); return base.VisitForStatement(node); } public override BoundNode? VisitForEachStatement(BoundForEachStatement node) { DeclareLocals(node.IterationVariables); return base.VisitForEachStatement(node); } public override BoundNode? VisitUsingStatement(BoundUsingStatement node) { DeclareLocals(node.Locals); Visit(node.AwaitOpt); return base.VisitUsingStatement(node); } public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { Visit(node.AwaitOpt); return base.VisitUsingLocalDeclarations(node); } public override BoundNode? VisitFixedStatement(BoundFixedStatement node) { DeclareLocals(node.Locals); return base.VisitFixedStatement(node); } public override BoundNode? VisitConstructorMethodBody(BoundConstructorMethodBody node) { DeclareLocals(node.Locals); return base.VisitConstructorMethodBody(node); } private void DeclareLocal(LocalSymbol local) { if (local.DeclarationKind != LocalDeclarationKind.None) { int slot = GetOrCreateSlot(local); if (slot > 0) { this.State[slot] = GetDefaultState(ref this.State, slot); InheritDefaultState(GetDeclaredLocalResult(local).Type, slot); } } } private void DeclareLocals(ImmutableArray<LocalSymbol> locals) { foreach (var local in locals) { DeclareLocal(local); } } public override BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); // We need visit the optional arguments so that we can return nullability information // about them, but we don't want to communicate any information about anything underneath. // Additionally, tests like Scope_DeclaratorArguments_06 can have conditional expressions // in the optional arguments that can leave us in a split state, so we want to make sure // we are not in a conditional state after. Debug.Assert(!IsConditionalState); var oldDisable = _disableDiagnostics; _disableDiagnostics = true; var currentState = State; VisitAndUnsplitAll(node.ArgumentsOpt); _disableDiagnostics = oldDisable; SetState(currentState); if (node.DeclaredTypeOpt != null) { VisitTypeExpression(node.DeclaredTypeOpt); } var initializer = node.InitializerOpt; if (initializer is null) { return null; } TypeWithAnnotations type = local.TypeWithAnnotations; TypeWithState valueType; bool inferredType = node.InferredType; if (local.IsRef) { valueType = VisitRefExpression(initializer, type); } else { valueType = VisitOptionalImplicitConversion(initializer, targetTypeOpt: inferredType ? default : type, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); Unsplit(); } if (inferredType) { if (valueType.HasNullType) { Debug.Assert(type.Type.IsErrorType()); valueType = type.ToTypeWithState(); } type = valueType.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local, type); if (node.DeclaredTypeOpt != null) { SetAnalyzedNullability(node.DeclaredTypeOpt, new VisitResult(type.ToTypeWithState(), type), true); } } TrackNullableStateForAssignment(initializer, type, slot, valueType, MakeSlot(initializer)); return null; } protected override BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node) { Debug.Assert(!IsConditionalState); SetInvalidResult(); _ = base.VisitExpressionWithoutStackGuard(node); TypeWithState resultType = ResultType; #if DEBUG // Verify Visit method set _result. Debug.Assert((object?)resultType.Type != _invalidType.Type); Debug.Assert(AreCloseEnough(resultType.Type, node.Type)); #endif if (ShouldMakeNotNullRvalue(node)) { var result = resultType.WithNotNullState(); SetResult(node, result, LvalueResultType); } return null; } #if DEBUG // For asserts only. private static bool AreCloseEnough(TypeSymbol? typeA, TypeSymbol? typeB) { // https://github.com/dotnet/roslyn/issues/34993: We should be able to tighten this to ensure that we're actually always returning the same type, // not error if one is null or ignoring certain types if ((object?)typeA == typeB) { return true; } if (typeA is null || typeB is null) { return typeA?.IsErrorType() != false && typeB?.IsErrorType() != false; } return canIgnoreAnyType(typeA) || canIgnoreAnyType(typeB) || typeA.Equals(typeB, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); // Ignore TupleElementNames (see https://github.com/dotnet/roslyn/issues/23651). static bool canIgnoreAnyType(TypeSymbol type) { return type.VisitType((t, unused1, unused2) => canIgnoreType(t), (object?)null) is object; } static bool canIgnoreType(TypeSymbol type) { return type.IsErrorType() || type.IsDynamic() || type.HasUseSiteError || (type.IsAnonymousType && canIgnoreAnonymousType((NamedTypeSymbol)type)); } static bool canIgnoreAnonymousType(NamedTypeSymbol type) { return AnonymousTypeManager.GetAnonymousTypeFieldTypes(type).Any(static t => canIgnoreAnyType(t.Type)); } } private static bool AreCloseEnough(Symbol original, Symbol updated) { // When https://github.com/dotnet/roslyn/issues/38195 is fixed, this workaround needs to be removed if (original is ConstructedMethodSymbol || updated is ConstructedMethodSymbol) { return AreCloseEnough(original.OriginalDefinition, updated.OriginalDefinition); } return (original, updated) switch { (LambdaSymbol l, NamedTypeSymbol n) _ when n.IsDelegateType() => AreLambdaAndNewDelegateSimilar(l, n), (FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var oi } originalField, FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var ui } updatedField) => originalField.Type.Equals(updatedField.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) && oi == ui, _ => original.Equals(updated, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) }; } #endif private static bool AreLambdaAndNewDelegateSimilar(LambdaSymbol l, NamedTypeSymbol n) { var invokeMethod = n.DelegateInvokeMethod; return invokeMethod!.Parameters.SequenceEqual(l.Parameters, (p1, p2) => p1.Type.Equals(p2.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) && invokeMethod.ReturnType.Equals(l.ReturnType, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames); } public override BoundNode? Visit(BoundNode? node) { return Visit(node, expressionIsRead: true); } private BoundNode VisitLValue(BoundNode node) { return Visit(node, expressionIsRead: false); } private BoundNode Visit(BoundNode? node, bool expressionIsRead) { #if DEBUG Debug.Assert(!_completingTargetTypedExpression); #endif bool originalExpressionIsRead = _expressionIsRead; _expressionIsRead = expressionIsRead; TakeIncrementalSnapshot(node); var result = base.Visit(node); _expressionIsRead = originalExpressionIsRead; return result; } protected override void VisitStatement(BoundStatement statement) { SetInvalidResult(); base.VisitStatement(statement); SetInvalidResult(); } public override BoundNode? VisitObjectCreationExpression(BoundObjectCreationExpression node) { VisitObjectCreationExpressionBase(node); return null; } public override BoundNode? VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { // This method is only involved in method inference with unbound lambdas. // The diagnostics on arguments are reported by VisitObjectCreationExpression. SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); return null; } private void VisitObjectCreationExpressionBase(BoundObjectCreationExpressionBase node) { Debug.Assert(!IsConditionalState); bool isTargetTyped = node.WasTargetTyped; MethodSymbol? constructor = getConstructor(node, node.Type); var arguments = node.Arguments; (_, ImmutableArray<VisitArgumentResult> argumentResults, _, ArgumentsCompletionDelegate? argumentsCompletion) = VisitArguments( node, arguments, node.ArgumentRefKindsOpt, constructor?.Parameters ?? default, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, invokedAsExtensionMethod: false, constructor, delayCompletionForTargetMember: isTargetTyped); Debug.Assert(isTargetTyped == argumentsCompletion is not null); var type = node.Type; (int slot, NullableFlowState resultState, Func<TypeSymbol, MethodSymbol?, int>? initialStateInferenceCompletion) = inferInitialObjectState(node, type, constructor, arguments, argumentResults, isTargetTyped); Action<int, TypeSymbol>? initializerCompletion = null; var initializerOpt = node.InitializerExpressionOpt; if (initializerOpt != null) { initializerCompletion = VisitObjectCreationInitializer(slot, type, initializerOpt, delayCompletionForType: isTargetTyped); } TypeWithState result = setAnalyzedNullability(node, type, argumentResults, argumentsCompletion, initialStateInferenceCompletion, initializerCompletion, resultState, isTargetTyped); SetResultType(node, result, updateAnalyzedNullability: false); return; TypeWithState setAnalyzedNullability( BoundObjectCreationExpressionBase node, TypeSymbol? type, ImmutableArray<VisitArgumentResult> argumentResults, ArgumentsCompletionDelegate? argumentsCompletion, Func<TypeSymbol, MethodSymbol?, int>? initialStateInferenceCompletion, Action<int, TypeSymbol>? initializerCompletion, NullableFlowState resultState, bool isTargetTyped) { var result = TypeWithState.Create(type, resultState); if (isTargetTyped) { Debug.Assert(argumentsCompletion is not null); Debug.Assert(initialStateInferenceCompletion is not null); setAnalyzedNullabilityAsContinuation(node, argumentResults, argumentsCompletion, initialStateInferenceCompletion, initializerCompletion, resultState); } else { Debug.Assert(argumentsCompletion is null); Debug.Assert(initialStateInferenceCompletion is null); Debug.Assert(initializerCompletion is null); SetAnalyzedNullability(node, result); } return result; } void setAnalyzedNullabilityAsContinuation( BoundObjectCreationExpressionBase node, ImmutableArray<VisitArgumentResult> argumentResults, ArgumentsCompletionDelegate argumentsCompletion, Func<TypeSymbol, MethodSymbol?, int> initialStateInferenceCompletion, Action<int, TypeSymbol>? initializerCompletion, NullableFlowState resultState) { Debug.Assert(resultState == NullableFlowState.NotNull); TargetTypedAnalysisCompletion[node] = (TypeWithAnnotations resultTypeWithAnnotations) => { Debug.Assert(TypeSymbol.Equals(resultTypeWithAnnotations.Type, node.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); var arguments = node.Arguments; var type = resultTypeWithAnnotations.Type; MethodSymbol? constructor = getConstructor(node, type); argumentsCompletion(argumentResults, constructor?.Parameters ?? default, constructor); int slot = initialStateInferenceCompletion(type, constructor); initializerCompletion?.Invoke(slot, type); return setAnalyzedNullability( node, type, argumentResults, argumentsCompletion: null, initialStateInferenceCompletion: null, initializerCompletion: null, resultState, isTargetTyped: false); }; } static MethodSymbol? getConstructor(BoundObjectCreationExpressionBase node, TypeSymbol type) { var constructor = node.Constructor; if (constructor is not null && !type.IsInterfaceType()) { constructor = (MethodSymbol)AsMemberOfType(type, constructor); } return constructor; } (int slot, NullableFlowState resultState, Func<TypeSymbol, MethodSymbol?, int>? completion) inferInitialObjectState( BoundExpression node, TypeSymbol type, MethodSymbol? constructor, ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> argumentResults, bool isTargetTyped) { if (isTargetTyped) { return (-1, NullableFlowState.NotNull, inferInitialObjectStateAsContinuation(node, arguments, argumentResults)); } Debug.Assert(node.Kind is BoundKind.ObjectCreationExpression or BoundKind.DynamicObjectCreationExpression or BoundKind.NewT or BoundKind.NoPiaObjectCreationExpression); var argumentTypes = argumentResults.SelectAsArray(ar => ar.RValueType); int slot = -1; var resultState = NullableFlowState.NotNull; if (type is object) { slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { bool isDefaultValueTypeConstructor = constructor?.IsDefaultValueTypeConstructor() == true; if (EmptyStructTypeCache.IsTrackableStructType(type)) { var containingType = constructor?.ContainingType; if (containingType?.IsTupleType == true && !isDefaultValueTypeConstructor) { // new System.ValueTuple<T1, ..., TN>(e1, ..., eN) TrackNullableStateOfTupleElements(slot, containingType, arguments, argumentTypes, ((BoundObjectCreationExpression)node).ArgsToParamsOpt, useRestField: true); } else { InheritNullableStateOfTrackableStruct( type, slot, valueSlot: -1, isDefaultValue: isDefaultValueTypeConstructor); } } else if (type.IsNullableType()) { if (isDefaultValueTypeConstructor) { // a nullable value type created with its default constructor is by definition null resultState = NullableFlowState.MaybeNull; } else if (constructor?.ParameterCount == 1) { // if we deal with one-parameter ctor that takes underlying, then Value state is inferred from the argument. var parameterType = constructor.ParameterTypesWithAnnotations[0]; if (AreNullableAndUnderlyingTypes(type, parameterType.Type, out TypeWithAnnotations underlyingType)) { var operand = arguments[0]; int valueSlot = MakeSlot(operand); if (valueSlot > 0) { TrackNullableStateOfNullableValue(slot, type, operand, underlyingType.ToTypeWithState(), valueSlot); } } } } this.State[slot] = resultState; } } return (slot, resultState, null); } Func<TypeSymbol, MethodSymbol?, int> inferInitialObjectStateAsContinuation( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> argumentResults) { return (TypeSymbol type, MethodSymbol? constructor) => { var (slot, resultState, completion) = inferInitialObjectState(node, type, constructor, arguments, argumentResults, isTargetTyped: false); Debug.Assert(completion is null); Debug.Assert(resultState == NullableFlowState.NotNull); return slot; }; } } /// <summary> /// If <paramref name="delayCompletionForType"/>, <paramref name="containingSlot"/> is known only within returned delegate. /// </summary> /// <returns>A delegate to complete the initializer analysis.</returns> private Action<int, TypeSymbol>? VisitObjectCreationInitializer(int containingSlot, TypeSymbol containingType, BoundObjectInitializerExpressionBase node, bool delayCompletionForType) { Debug.Assert(!delayCompletionForType || containingSlot == -1); Action<int, TypeSymbol>? completion = null; TakeIncrementalSnapshot(node); switch (node) { case BoundObjectInitializerExpression objectInitializer: foreach (var initializer in objectInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.AssignmentOperator: completion += VisitObjectElementInitializer(containingSlot, containingType, (BoundAssignmentOperator)initializer, delayCompletionForType); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(objectInitializer.Placeholder); break; case BoundCollectionInitializerExpression collectionInitializer: foreach (var initializer in collectionInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.CollectionElementInitializer: completion += VisitCollectionElementInitializer((BoundCollectionElementInitializer)initializer, containingType, delayCompletionForType); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(collectionInitializer.Placeholder); break; default: ExceptionUtilities.UnexpectedValue(node.Kind); break; } return completion; } /// <summary> /// If <paramref name="delayCompletionForType"/>, <paramref name="containingSlot"/> is known only within returned delegate. /// </summary> /// <returns>A delegate to complete the element initializer analysis.</returns> private Action<int, TypeSymbol>? VisitObjectElementInitializer(int containingSlot, TypeSymbol containingType, BoundAssignmentOperator node, bool delayCompletionForType) { Debug.Assert(!delayCompletionForType || containingSlot == -1); TakeIncrementalSnapshot(node); var left = node.Left; switch (left.Kind) { case BoundKind.ObjectInitializerMember: { TakeIncrementalSnapshot(left); return visitMemberInitializer(containingSlot, containingType, node, delayCompletionForType); } default: VisitRvalue(node); return null; } Action<int, TypeSymbol>? visitMemberInitializer(int containingSlot, TypeSymbol containingType, BoundAssignmentOperator node, bool delayCompletionForType) { var objectInitializer = (BoundObjectInitializerMember)node.Left; Symbol? symbol = getTargetMember(containingType, objectInitializer); ImmutableArray<VisitArgumentResult> argumentResults = default; ArgumentsCompletionDelegate? argumentsCompletion = null; if (!objectInitializer.Arguments.IsDefaultOrEmpty) { // It is an error for an interpolated string to use the receiver of an object initializer indexer here, so we just use // a default visit result (_, argumentResults, _, argumentsCompletion) = VisitArguments( objectInitializer, objectInitializer.Arguments, objectInitializer.ArgumentRefKindsOpt, ((PropertySymbol?)symbol)?.Parameters ?? default, objectInitializer.ArgsToParamsOpt, objectInitializer.DefaultArguments, objectInitializer.Expanded, invokedAsExtensionMethod: false, method: null, delayCompletionForTargetMember: delayCompletionForType); } Action<int, Symbol>? initializationCompletion = null; if (symbol is object) { if (node.Right is BoundObjectInitializerExpressionBase initializer) { initializationCompletion = visitNestedInitializer(containingSlot, containingType, symbol, initializer, delayCompletionForType); } else { TakeIncrementalSnapshot(node.Right); initializationCompletion = visitMemberAssignment(node, containingSlot, symbol, delayCompletionForType); } // https://github.com/dotnet/roslyn/issues/35040: Should likely be setting _resultType in VisitObjectCreationInitializer // and using that value instead of reconstructing here } return setAnalyzedNullability(node, argumentResults, argumentsCompletion, initializationCompletion, delayCompletionForType); } Action<int, TypeSymbol>? setAnalyzedNullability( BoundAssignmentOperator node, ImmutableArray<VisitArgumentResult> argumentResults, ArgumentsCompletionDelegate? argumentsCompletion, Action<int, Symbol>? initializationCompletion, bool delayCompletionForType) { if (delayCompletionForType) { return setAnalyzedNullabilityAsContinuation(node, argumentResults, argumentsCompletion, initializationCompletion); } Debug.Assert(argumentsCompletion is null); Debug.Assert(initializationCompletion is null); var objectInitializer = (BoundObjectInitializerMember)node.Left; var result = new VisitResult(objectInitializer.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull); SetAnalyzedNullability(objectInitializer, result); SetAnalyzedNullability(node, result); return null; } Action<int, TypeSymbol>? setAnalyzedNullabilityAsContinuation( BoundAssignmentOperator node, ImmutableArray<VisitArgumentResult> argumentResults, ArgumentsCompletionDelegate? argumentsCompletion, Action<int, Symbol>? initializationCompletion) { return (int containingSlot, TypeSymbol containingType) => { Symbol? symbol = getTargetMember(containingType, (BoundObjectInitializerMember)node.Left); Debug.Assert(initializationCompletion is null || symbol is not null); argumentsCompletion?.Invoke(argumentResults, ((PropertySymbol?)symbol)?.Parameters ?? default, null); initializationCompletion?.Invoke(containingSlot, symbol!); var result = setAnalyzedNullability(node, argumentResults, argumentsCompletion: null, initializationCompletion: null, delayCompletionForType: false); Debug.Assert(result is null); }; } static Symbol? getTargetMember(TypeSymbol containingType, BoundObjectInitializerMember objectInitializer) { var symbol = objectInitializer.MemberSymbol; if (symbol != null) { Debug.Assert(TypeSymbol.Equals(objectInitializer.Type, symbol.GetTypeOrReturnType().Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); symbol = AsMemberOfType(containingType, symbol); } return symbol; } int getOrCreateSlot(int containingSlot, Symbol symbol) { return (containingSlot < 0 || !IsSlotMember(containingSlot, symbol)) ? -1 : GetOrCreateSlot(symbol, containingSlot); } Action<int, Symbol>? visitNestedInitializer(int containingSlot, TypeSymbol containingType, Symbol symbol, BoundObjectInitializerExpressionBase initializer, bool delayCompletionForType) { int slot = getOrCreateSlot(containingSlot, symbol); Debug.Assert(!delayCompletionForType || slot == -1); Action<int, TypeSymbol>? nestedCompletion = VisitObjectCreationInitializer(slot, symbol.GetTypeOrReturnType().Type, initializer, delayCompletionForType); return completeNestedInitializerAnalysis(symbol, initializer, slot, nestedCompletion, delayCompletionForType); } Action<int, Symbol>? completeNestedInitializerAnalysis( Symbol symbol, BoundObjectInitializerExpressionBase initializer, int slot, Action<int, TypeSymbol>? nestedCompletion, bool delayCompletionForType) { if (delayCompletionForType) { return completeNestedInitializerAnalysisAsContinuation(initializer, nestedCompletion); } Debug.Assert(nestedCompletion is null); if (slot >= 0 && !initializer.Initializers.IsEmpty) { if (!initializer.Type.IsValueType && State[slot].MayBeNull()) { ReportDiagnostic(ErrorCode.WRN_NullReferenceInitializer, initializer.Syntax, symbol); } } return null; } Action<int, Symbol>? completeNestedInitializerAnalysisAsContinuation(BoundObjectInitializerExpressionBase initializer, Action<int, TypeSymbol>? nestedCompletion) { return (int containingSlot, Symbol symbol) => { int slot = getOrCreateSlot(containingSlot, symbol); completeNestedInitializerAnalysis(symbol, initializer, slot, nestedCompletion: null, delayCompletionForType: false); nestedCompletion?.Invoke(slot, symbol.GetTypeOrReturnType().Type); }; } Action<int, Symbol>? visitMemberAssignment(BoundAssignmentOperator node, int containingSlot, Symbol symbol, bool delayCompletionForType, Func<TypeWithAnnotations, TypeWithState>? conversionCompletion = null) { Debug.Assert(!delayCompletionForType || conversionCompletion is null); if (!delayCompletionForType && conversionCompletion is null) { TakeIncrementalSnapshot(node.Right); } Debug.Assert(symbol.GetTypeOrReturnType().HasType); var type = ApplyLValueAnnotations(symbol.GetTypeOrReturnType(), GetObjectInitializerMemberLValueAnnotations(symbol)); (TypeWithState resultType, conversionCompletion) = conversionCompletion is not null ? (conversionCompletion(type), null) : VisitOptionalImplicitConversion(node.Right, type, useLegacyWarnings: false, trackMembers: true, AssignmentKind.Assignment, delayCompletionForType); Unsplit(); if (delayCompletionForType) { Debug.Assert(conversionCompletion is not null); return visitMemberAssignmentAsContinuation(node, conversionCompletion); } Debug.Assert(conversionCompletion is null); int slot = getOrCreateSlot(containingSlot, symbol); TrackNullableStateForAssignment(node.Right, type, slot, resultType, MakeSlot(node.Right)); return null; } Action<int, Symbol>? visitMemberAssignmentAsContinuation(BoundAssignmentOperator node, Func<TypeWithAnnotations, TypeWithState> conversionCompletion) { return (int containingSlot, Symbol symbol) => { var result = visitMemberAssignment(node, containingSlot, symbol, delayCompletionForType: false, conversionCompletion); Debug.Assert(result is null); }; } } [Obsolete("Use VisitCollectionElementInitializer(BoundCollectionElementInitializer node, TypeSymbol containingType, bool delayCompletionForType) instead.", true)] #pragma warning disable IDE0051 // Remove unused private members private new void VisitCollectionElementInitializer(BoundCollectionElementInitializer node) #pragma warning restore IDE0051 // Remove unused private members { throw ExceptionUtilities.Unreachable; } private Action<int, TypeSymbol>? VisitCollectionElementInitializer(BoundCollectionElementInitializer node, TypeSymbol containingType, bool delayCompletionForType) { ImmutableArray<VisitArgumentResult> argumentResults = default; MethodSymbol addMethod = addMethodAsMemberOfContainingType(node, containingType, ref argumentResults); // Note: we analyze even omitted calls (MethodSymbol? reinferredMethod, argumentResults, _, ArgumentsCompletionDelegate? visitArgumentsCompletion) = VisitArguments( node, node.Arguments, refKindsOpt: default, addMethod.Parameters, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod, addMethod, delayCompletionForTargetMember: delayCompletionForType); #if DEBUG if (node.InvokedAsExtensionMethod) { VisitArgumentResult receiverResult = argumentResults[0]; Debug.Assert(TypeSymbol.Equals(containingType, receiverResult.VisitResult.RValueType.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); Debug.Assert(TypeSymbol.Equals(containingType, receiverResult.LValueType.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); } #endif return setUpdatedSymbol(node, containingType, reinferredMethod, argumentResults, visitArgumentsCompletion, delayCompletionForType); Action<int, TypeSymbol>? setUpdatedSymbol( BoundCollectionElementInitializer node, TypeSymbol containingType, MethodSymbol? reinferredMethod, ImmutableArray<VisitArgumentResult> argumentResults, ArgumentsCompletionDelegate? visitArgumentsCompletion, bool delayCompletionForType) { if (delayCompletionForType) { Debug.Assert(visitArgumentsCompletion is not null); return setUpdatedSymbolAsContinuation(node, argumentResults, visitArgumentsCompletion); } Debug.Assert(visitArgumentsCompletion is null); Debug.Assert(reinferredMethod is object); if (node.ImplicitReceiverOpt != null) { Debug.Assert(node.ImplicitReceiverOpt.Kind == BoundKind.ObjectOrCollectionValuePlaceholder); SetAnalyzedNullability(node.ImplicitReceiverOpt, new VisitResult(node.ImplicitReceiverOpt.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull)); } SetUnknownResultNullability(node); SetUpdatedSymbol(node, node.AddMethod, reinferredMethod); return null; } Action<int, TypeSymbol>? setUpdatedSymbolAsContinuation( BoundCollectionElementInitializer node, ImmutableArray<VisitArgumentResult> argumentResults, ArgumentsCompletionDelegate visitArgumentsCompletion) { return (int containingSlot, TypeSymbol containingType) => { MethodSymbol addMethod = addMethodAsMemberOfContainingType(node, containingType, ref argumentResults); setUpdatedSymbol( node, containingType, visitArgumentsCompletion.Invoke(argumentResults, addMethod.Parameters, addMethod).method, argumentResults, visitArgumentsCompletion: null, delayCompletionForType: false); }; } static MethodSymbol addMethodAsMemberOfContainingType(BoundCollectionElementInitializer node, TypeSymbol containingType, ref ImmutableArray<VisitArgumentResult> argumentResults) { var method = node.AddMethod; if (node.InvokedAsExtensionMethod) { if (!argumentResults.IsDefault) { VisitArgumentResult receiverResult = argumentResults[0]; Debug.Assert(TypeSymbol.Equals(containingType, receiverResult.VisitResult.RValueType.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); Debug.Assert(TypeSymbol.Equals(containingType, receiverResult.LValueType.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); var builder = ArrayBuilder<VisitArgumentResult>.GetInstance(argumentResults.Length); builder.Add( new VisitArgumentResult( new VisitResult( TypeWithState.Create(containingType, receiverResult.RValueType.State), receiverResult.LValueType.WithType(containingType)), receiverResult.StateForLambda)); builder.AddRange(argumentResults, 1, argumentResults.Length - 1); argumentResults = builder.ToImmutableAndFree(); } } else { method = (MethodSymbol)AsMemberOfType(containingType, method); } return method; } } private void SetNotNullResult(BoundExpression node) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); } /// <summary> /// Returns true if the type is a struct with no fields or properties. /// </summary> protected override bool IsEmptyStructType(TypeSymbol type) { if (type.TypeKind != TypeKind.Struct) { return false; } // EmptyStructTypeCache.IsEmptyStructType() returns false // if there are non-cyclic fields. if (!_emptyStructTypeCache.IsEmptyStructType(type)) { return false; } if (type.SpecialType != SpecialType.None) { return true; } var members = ((NamedTypeSymbol)type).GetMembersUnordered(); // EmptyStructTypeCache.IsEmptyStructType() returned true. If there are fields, // at least one of those fields must be cyclic, so treat the type as empty. if (members.Any(static m => m.Kind == SymbolKind.Field)) { return true; } // If there are properties, the type is not empty. if (members.Any(static m => m.Kind == SymbolKind.Property)) { return false; } return true; } private int GetOrCreatePlaceholderSlot(BoundExpression node) { Debug.Assert(node.Type is object); if (IsEmptyStructType(node.Type)) { return -1; } return GetOrCreatePlaceholderSlot(node, TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated)); } private int GetOrCreatePlaceholderSlot(object identifier, TypeWithAnnotations type) { _placeholderLocalsOpt ??= PooledDictionary<object, PlaceholderLocal>.GetInstance(); if (!_placeholderLocalsOpt.TryGetValue(identifier, out var placeholder)) { placeholder = new PlaceholderLocal(CurrentSymbol, identifier, type); _placeholderLocalsOpt.Add(identifier, placeholder); } Debug.Assert((object)placeholder != null); return GetOrCreateSlot(placeholder, forceSlotEvenIfEmpty: true); } public override BoundNode? VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { Debug.Assert(!IsConditionalState); Debug.Assert(node.Type.IsAnonymousType); var anonymousType = (NamedTypeSymbol)node.Type; var arguments = node.Arguments; var argumentTypes = arguments.SelectAsArray((arg, self) => self.VisitRvalueWithState(arg), this); var argumentsWithAnnotations = argumentTypes.SelectAsArray(arg => arg.ToTypeWithAnnotations(compilation)); if (argumentsWithAnnotations.All(argType => argType.HasType)) { anonymousType = AnonymousTypeManager.ConstructAnonymousTypeSymbol(anonymousType, argumentsWithAnnotations); int receiverSlot = GetOrCreatePlaceholderSlot(node); int currentDeclarationIndex = 0; for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var argumentType = argumentTypes[i]; var property = AnonymousTypeManager.GetAnonymousTypeProperty(anonymousType, i); if (property.Type.SpecialType != SpecialType.System_Void) { // A void element results in an error type in the anonymous type but not in the property's container! // To avoid failing an assertion later, we skip them. var slot = GetOrCreateSlot(property, receiverSlot); TrackNullableStateForAssignment(argument, property.TypeWithAnnotations, slot, argumentType, MakeSlot(argument)); var currentDeclaration = getDeclaration(node, property, ref currentDeclarationIndex); if (currentDeclaration is object) { TakeIncrementalSnapshot(currentDeclaration); SetAnalyzedNullability(currentDeclaration, new VisitResult(argumentType, property.TypeWithAnnotations)); } } } } SetResultType(node, TypeWithState.Create(anonymousType, NullableFlowState.NotNull)); return null; static BoundAnonymousPropertyDeclaration? getDeclaration(BoundAnonymousObjectCreationExpression node, PropertySymbol currentProperty, ref int currentDeclarationIndex) { if (currentDeclarationIndex >= node.Declarations.Length) { return null; } var currentDeclaration = node.Declarations[currentDeclarationIndex]; if (currentDeclaration.Property.MemberIndexOpt == currentProperty.MemberIndexOpt) { currentDeclarationIndex++; return currentDeclaration; } return null; } } public override BoundNode? VisitArrayCreation(BoundArrayCreation node) { foreach (var expr in node.Bounds) { VisitRvalue(expr); } var initialization = node.InitializerOpt; if (initialization is null) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return null; } var arrayType = VisitArrayInitialization(node.Type, initialization, node.HasErrors); SetResultType(node, TypeWithState.Create(arrayType, NullableFlowState.NotNull)); return null; } private TypeSymbol VisitArrayInitialization(TypeSymbol type, BoundArrayInitialization initialization, bool hasErrors) { TakeIncrementalSnapshot(initialization); var expressions = ArrayBuilder<BoundExpression>.GetInstance(initialization.Initializers.Length); GetArrayElements(initialization, expressions); int n = expressions.Count; // Consider recording in the BoundArrayCreation // whether the array was implicitly typed, rather than relying on syntax. var elementType = type switch { ArrayTypeSymbol arrayType => arrayType.ElementTypeWithAnnotations, PointerTypeSymbol pointerType => pointerType.PointedAtTypeWithAnnotations, NamedTypeSymbol spanType => getSpanElementType(spanType), _ => throw ExceptionUtilities.UnexpectedValue(type.TypeKind) }; var resultType = type; if (!initialization.IsInferred) { foreach (var expr in expressions) { _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment); Unsplit(); } } else { var expressionsNoConversions = ArrayBuilder<BoundExpression>.GetInstance(n); var conversions = ArrayBuilder<Conversion>.GetInstance(n); var expressionTypes = ArrayBuilder<TypeWithState>.GetInstance(n); var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); foreach (var expression in expressions) { // collect expressions, conversions and result types (BoundExpression expressionNoConversion, Conversion conversion) = RemoveConversion(expression, includeExplicitConversions: false); expressionsNoConversions.Add(expressionNoConversion); conversions.Add(conversion); SnapshotWalkerThroughConversionGroup(expression, expressionNoConversion); var expressionType = VisitRvalueWithState(expressionNoConversion); expressionTypes.Add(expressionType); if (!IsTargetTypedExpression(expressionNoConversion)) { placeholderBuilder.Add(CreatePlaceholderIfNecessary(expressionNoConversion, expressionType.ToTypeWithAnnotations(compilation))); } } var placeholders = placeholderBuilder.ToImmutableAndFree(); TypeSymbol? bestType = null; if (!hasErrors) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bestType = BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo, out _); } TypeWithAnnotations inferredType = (bestType is null) ? elementType.SetUnknownNullabilityForReferenceTypes() : TypeWithAnnotations.Create(bestType); if (bestType is object) { // Convert elements to best type to determine element top-level nullability and to report nested nullability warnings for (int i = 0; i < n; i++) { var expressionNoConversion = expressionsNoConversions[i]; var expression = GetConversionIfApplicable(expressions[i], expressionNoConversion); expressionTypes[i] = VisitConversion(expression, expressionNoConversion, conversions[i], inferredType, expressionTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: true, reportTopLevelWarnings: false); } // Set top-level nullability on inferred element type var elementState = BestTypeInferrer.GetNullableState(expressionTypes); inferredType = TypeWithState.Create(inferredType.Type, elementState).ToTypeWithAnnotations(compilation); for (int i = 0; i < n; i++) { // Report top-level warnings _ = VisitConversion(conversionOpt: null, conversionOperand: expressionsNoConversions[i], Conversion.Identity, targetTypeWithNullability: inferredType, operandType: expressionTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: false); } } else { // We need to ensure that we're tracking the inferred type with nullability of any conversions that // were stripped off. for (int i = 0; i < n; i++) { TrackAnalyzedNullabilityThroughConversionGroup(inferredType.ToTypeWithState(), expressions[i] as BoundConversion, expressionsNoConversions[i]); } } expressionsNoConversions.Free(); conversions.Free(); expressionTypes.Free(); resultType = type switch { ArrayTypeSymbol arrayType => arrayType.WithElementType(inferredType), PointerTypeSymbol pointerType => pointerType.WithPointedAtType(inferredType), NamedTypeSymbol spanType => setSpanElementType(spanType, inferredType), _ => throw ExceptionUtilities.UnexpectedValue(type.TypeKind) }; } expressions.Free(); return resultType; static TypeWithAnnotations getSpanElementType(NamedTypeSymbol namedType) { Debug.Assert(namedType.Name == "Span"); Debug.Assert(namedType.OriginalDefinition.Arity == 1); return namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; } static TypeSymbol setSpanElementType(NamedTypeSymbol namedType, TypeWithAnnotations elementType) { Debug.Assert(namedType.Name == "Span"); Debug.Assert(namedType.OriginalDefinition.Arity == 1); return namedType.OriginalDefinition.Construct(ImmutableArray.Create(elementType)); } } private static bool IsTargetTypedExpression(BoundExpression node) { return node is BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true } or BoundObjectCreationExpressionBase { WasTargetTyped: true } or BoundDelegateCreationExpression { WasTargetTyped: true }; } /// <summary> /// Applies analysis similar to <see cref="VisitArrayCreation"/>. /// The expressions returned from a lambda are not converted though, so we'll have to classify fresh conversions. /// Note: even if some conversions fail, we'll proceed to infer top-level nullability. That is reasonable in common cases. /// </summary> internal static TypeWithAnnotations BestTypeForLambdaReturns( ArrayBuilder<(BoundExpression expr, TypeWithAnnotations resultType, bool isChecked)> returns, Binder binder, BoundNode node, Conversions conversions, out bool inferredFromFunctionType) { var walker = new NullableWalker(binder.Compilation, symbol: null, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, conversions: conversions, variables: null, baseOrThisInitializer: null, returnTypesOpt: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); int n = returns.Count; var resultTypes = ArrayBuilder<TypeWithAnnotations>.GetInstance(n); var placeholdersBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var (returnExpr, resultType, _) = returns[i]; resultTypes.Add(resultType); placeholdersBuilder.Add(CreatePlaceholderIfNecessary(returnExpr, resultType)); } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var placeholders = placeholdersBuilder.ToImmutableAndFree(); TypeSymbol? bestType = BestTypeInferrer.InferBestType(placeholders, walker._conversions, ref discardedUseSiteInfo, out inferredFromFunctionType); TypeWithAnnotations inferredType; if (bestType is { }) { // Note: so long as we have a best type, we can proceed. var bestTypeWithObliviousAnnotation = TypeWithAnnotations.Create(bestType); Conversions conversionsWithoutNullability = walker._conversions.WithNullability(false); for (int i = 0; i < n; i++) { BoundExpression placeholder = placeholders[i]; Conversion conversion = conversionsWithoutNullability.ClassifyConversionFromExpression(placeholder, bestType, isChecked: returns[i].isChecked, ref discardedUseSiteInfo); resultTypes[i] = walker.VisitConversion(conversionOpt: null, placeholder, conversion, bestTypeWithObliviousAnnotation, resultTypes[i].ToTypeWithState(), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Return, reportRemainingWarnings: false, reportTopLevelWarnings: false).ToTypeWithAnnotations(binder.Compilation); } // Set top-level nullability on inferred type inferredType = TypeWithAnnotations.Create(bestType, BestTypeInferrer.GetNullableAnnotation(resultTypes)); } else { inferredType = default; } resultTypes.Free(); walker.Free(); return inferredType; } private static void GetArrayElements(BoundArrayInitialization node, ArrayBuilder<BoundExpression> builder) { foreach (var child in node.Initializers) { if (child.Kind == BoundKind.ArrayInitialization) { GetArrayElements((BoundArrayInitialization)child, builder); } else { builder.Add(child); } } } public override BoundNode? VisitArrayAccess(BoundArrayAccess node) { Debug.Assert(!IsConditionalState); Visit(node.Expression); Debug.Assert(!IsConditionalState); Debug.Assert(!node.Expression.Type!.IsValueType); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(node.Expression); var type = ResultType.Type as ArrayTypeSymbol; foreach (var i in node.Indices) { VisitRvalue(i); } TypeWithAnnotations result; if (node.Indices.Length == 1 && TypeSymbol.Equals(node.Indices[0].Type, compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything2)) { result = TypeWithAnnotations.Create(type); } else { result = type?.ElementTypeWithAnnotations ?? default; } SetLvalueResultType(node, result); return null; } private TypeWithState InferResultNullability(BinaryOperatorKind operatorKind, MethodSymbol? methodOpt, TypeSymbol resultType, TypeWithState leftType, TypeWithState rightType) { NullableFlowState resultState = NullableFlowState.NotNull; if (operatorKind.IsUserDefined()) { if (methodOpt?.ParameterCount == 2) { if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { return GetLiftedReturnType(methodOpt.ReturnTypeWithAnnotations, leftType.State.Join(rightType.State)); } var resultTypeWithState = GetReturnTypeWithState(methodOpt); if ((leftType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[0].Name)) || (rightType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[1].Name))) { resultTypeWithState = resultTypeWithState.WithNotNullState(); } return resultTypeWithState; } } else if (!operatorKind.IsDynamic() && !resultType.IsValueType) { switch (operatorKind.Operator() | operatorKind.OperandTypes()) { case BinaryOperatorKind.DelegateCombination: resultState = leftType.State.Meet(rightType.State); break; case BinaryOperatorKind.DelegateRemoval: resultState = NullableFlowState.MaybeNull; // Delegate removal can produce null. break; default: resultState = NullableFlowState.NotNull; break; } } if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { resultState = leftType.State.Join(rightType.State); } return TypeWithState.Create(resultType, resultState); } protected override void VisitBinaryOperatorChildren(ArrayBuilder<BoundBinaryOperator> stack) { var binary = stack.Pop(); var (leftOperand, leftConversion) = RemoveConversion(binary.Left, includeExplicitConversions: false); // Only the leftmost operator of a left-associative binary operator chain can learn from a conditional access on the left // For simplicity, we just special case it here. // For example, `a?.b(out x) == true` has a conditional access on the left of the operator, // but `expr == a?.b(out x) == true` has a conditional access on the right of the operator if (VisitPossibleConditionalAccess(leftOperand, out var conditionalStateWhenNotNull) && CanPropagateStateWhenNotNull(leftConversion) && binary.OperatorKind.Operator() is BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // Consider the following two scenarios: // `a?.b(x = new object()) == c.d(x = null)` // `x` is maybe-null after expression // `a?.b(x = null) == c.d(x = new object())` // `x` is not-null after expression // In this scenario, we visit the RHS twice: // (1) Once using the single "stateWhenNotNull" after the LHS, in order to update the "stateWhenNotNull" with the effects of the RHS // (2) Once using the "worst case" state after the LHS for diagnostics and public API // After the two visits of the RHS, we may set a conditional state using the state after (1) as the StateWhenTrue and the state after (2) as the StateWhenFalse. // Depending on whether `==` or `!=` was used, and depending on the value of the RHS, we may then swap the StateWhenTrue with the StateWhenFalse. var oldDisableDiagnostics = _disableDiagnostics; _disableDiagnostics = true; var stateAfterLeft = this.State; SetState(getUnconditionalStateWhenNotNull(rightOperand, conditionalStateWhenNotNull)); VisitRvalue(rightOperand); var stateWhenNotNull = this.State; _disableDiagnostics = oldDisableDiagnostics; // Now visit the right side for public API and diagnostics using the worst-case state from the LHS. // Note that we do this visit last to try and make sure that the "visit for public API" overwrites walker state recorded during previous visits where possible. SetState(stateAfterLeft); var rightType = VisitRvalueWithState(rightOperand); ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); if (isKnownNullOrNotNull(rightOperand, rightType)) { var isNullConstant = rightOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); } if (stack.Count == 0) { return; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } while (true) { if (!learnFromConditionalAccessOrBoolConstant()) { Unsplit(); // VisitRvalue does this UseRvalueOnly(leftOperand); // drop lvalue part AfterLeftChildHasBeenVisited(leftOperand, leftConversion, binary); } if (stack.Count == 0) { break; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } static bool isEquals(BoundBinaryOperator binary) => binary.OperatorKind.Operator() == BinaryOperatorKind.Equal; static bool isKnownNullOrNotNull(BoundExpression expr, TypeWithState resultType) { return resultType.State.IsNotNull() || expr.ConstantValue is object; } LocalState getUnconditionalStateWhenNotNull(BoundExpression otherOperand, PossiblyConditionalState conditionalStateWhenNotNull) { LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else if (isEquals(binary) && otherOperand.ConstantValue is { IsBoolean: true, BooleanValue: var boolValue }) { // can preserve conditional state from `.TryGetValue` in `dict?.TryGetValue(key, out value) == true`, // but not in `dict?.TryGetValue(key, out value) != false` stateWhenNotNull = boolValue ? conditionalStateWhenNotNull.StateWhenTrue : conditionalStateWhenNotNull.StateWhenFalse; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } return stateWhenNotNull; } // Returns true if `binary.Right` was visited by the call. bool learnFromConditionalAccessOrBoolConstant() { if (binary.OperatorKind.Operator() is not (BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual)) { return false; } var leftResult = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // `true == a?.b(out x)` if (isKnownNullOrNotNull(leftOperand, leftResult) && CanPropagateStateWhenNotNull(rightConversion) && TryVisitConditionalAccess(rightOperand, out var conditionalStateWhenNotNull)) { ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftResult, rightOperand, rightConversion, rightType: ResultType, binary); var stateWhenNotNull = getUnconditionalStateWhenNotNull(leftOperand, conditionalStateWhenNotNull); var isNullConstant = leftOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); return true; } // can only learn from a bool constant operand here if it's using the built in `bool operator ==(bool left, bool right)` if (binary.OperatorKind.IsUserDefined()) { return false; } // `(x != null) == true` if (IsConditionalState && binary.Right.ConstantValue is { IsBoolean: true } rightConstant) { var (stateWhenTrue, stateWhenFalse) = (StateWhenTrue.Clone(), StateWhenFalse.Clone()); Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); // record result for the right SetConditionalState(isEquals(binary) == rightConstant.BooleanValue ? (stateWhenTrue, stateWhenFalse) : (stateWhenFalse, stateWhenTrue)); } // `true == (x != null)` else if (binary.Left.ConstantValue is { IsBoolean: true } leftConstant) { Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); if (IsConditionalState && isEquals(binary) != leftConstant.BooleanValue) { SetConditionalState(StateWhenFalse, StateWhenTrue); } } else { return false; } // record result for the binary Debug.Assert(binary.Type.SpecialType == SpecialType.System_Boolean); SetResult(binary, TypeWithState.ForType(binary.Type), TypeWithAnnotations.Create(binary.Type)); return true; } } private void ReinferBinaryOperatorAndSetResult( BoundExpression leftOperand, Conversion leftConversion, TypeWithState leftType, BoundExpression rightOperand, Conversion rightConversion, TypeWithState rightType, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); // At this point, State.Reachable may be false for // invalid code such as `s + throw new Exception()`. var method = binary.Method; if (binary.OperatorKind.IsUserDefined() && method?.ParameterCount == 2) { // Update method based on inferred operand type. TypeSymbol methodContainer = method.ContainingType; bool isLifted = binary.OperatorKind.IsLifted(); TypeWithState leftUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, leftType); TypeWithState rightUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, rightType); TypeSymbol asMemberOfType = getTypeIfContainingType(methodContainer, leftUnderlyingType.Type, leftOperand) ?? getTypeIfContainingType(methodContainer, rightUnderlyingType.Type, rightOperand) ?? methodContainer; method = (MethodSymbol)AsMemberOfType(asMemberOfType, method); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameters = method.Parameters; visitOperandConversionAndPostConditions(binary.Left, leftOperand, leftConversion, parameters[0], leftUnderlyingType); visitOperandConversionAndPostConditions(binary.Right, rightOperand, rightConversion, parameters[1], rightUnderlyingType); SetUpdatedSymbol(binary, binary.Method!, method); void visitOperandConversionAndPostConditions( BoundExpression expr, BoundExpression operand, Conversion conversion, ParameterSymbol parameter, TypeWithState operandType) { var parameterAnnotations = GetParameterAnnotations(parameter); var targetTypeWithNullability = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); if (isLifted && targetTypeWithNullability.Type.IsNonNullableValueType()) { targetTypeWithNullability = TypeWithAnnotations.Create(MakeNullableOf(targetTypeWithNullability)); } var resultType = VisitConversion( expr as BoundConversion, operand, conversion, targetTypeWithNullability, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument, parameter); CheckDisallowedNullAssignment(resultType, parameterAnnotations, expr.Syntax.Location, operand); LearnFromPostConditions(operand, parameterAnnotations); } } else { // Assume this is a built-in operator in which case the parameter types are unannotated. visitOperandConversion(binary.Left, leftOperand, leftConversion, leftType); visitOperandConversion(binary.Right, rightOperand, rightConversion, rightType); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, TypeWithState operandType) { if (expr.Type is null) { Debug.Assert(operand == expr); } else { _ = VisitConversion( expr as BoundConversion, operand, conversion, TypeWithAnnotations.Create(expr.Type), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument); } } } Debug.Assert(!IsConditionalState); if (binary.OperatorKind.IsLifted() && binary.OperatorKind.Operator() is BinaryOperatorKind.GreaterThan or BinaryOperatorKind.GreaterThanOrEqual or BinaryOperatorKind.LessThan or BinaryOperatorKind.LessThanOrEqual) { Debug.Assert(binary.Type.SpecialType == SpecialType.System_Boolean); SplitAndLearnFromNonNullTest(binary.Left, whenTrue: true); SplitAndLearnFromNonNullTest(binary.Right, whenTrue: true); } // For nested binary operators, this can be the only time they're visited due to explicit stack used in AbstractFlowPass.VisitBinaryOperator, // so we need to set the flow-analyzed type here. var inferredResult = InferResultNullability(binary.OperatorKind, method, binary.Type, leftType, rightType); SetResult(binary, inferredResult, inferredResult.ToTypeWithAnnotations(compilation)); return; TypeSymbol? getTypeIfContainingType(TypeSymbol baseType, TypeSymbol? derivedType, BoundExpression operand) { if (derivedType is null || IsTargetTypedExpression(operand)) { return null; } derivedType = derivedType.StrippedType(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyBuiltInConversion(derivedType, baseType, isChecked: false, ref discardedUseSiteInfo); if (conversion.Exists && !conversion.IsExplicit) { return derivedType; } return null; } } private void AfterLeftChildHasBeenVisited( BoundExpression leftOperand, Conversion leftConversion, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); VisitRvalue(rightOperand); var rightType = ResultType; ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); BinaryOperatorKind op = binary.OperatorKind.Operator(); if (op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) { // learn from null constant BoundExpression? operandComparedToNull = null; if (binary.Right.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Left; } else if (binary.Left.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Right; } if (operandComparedToNull != null) { // Set all nested conditional slots. For example in a?.b?.c we'll set a, b, and c. bool nonNullCase = op != BinaryOperatorKind.Equal; // true represents WhenTrue SplitAndLearnFromNonNullTest(operandComparedToNull, whenTrue: nonNullCase); // `x == null` and `x != null` are pure null tests so update the null-state in the alternative branch too LearnFromNullTest(operandComparedToNull, ref nonNullCase ? ref StateWhenFalse : ref StateWhenTrue); return; } } // learn from comparison between non-null and maybe-null, possibly updating maybe-null to non-null BoundExpression? operandComparedToNonNull = null; if (leftType.IsNotNull && rightType.MayBeNull) { operandComparedToNonNull = binary.Right; } else if (rightType.IsNotNull && leftType.MayBeNull) { operandComparedToNonNull = binary.Left; } if (operandComparedToNonNull != null) { switch (op) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.LessThan: case BinaryOperatorKind.GreaterThanOrEqual: case BinaryOperatorKind.LessThanOrEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); SplitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: true); return; case BinaryOperatorKind.NotEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); SplitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: false); return; }; } } private void SplitAndLearnFromNonNullTest(BoundExpression operandComparedToNonNull, bool whenTrue) { var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(operandComparedToNonNull, slotBuilder); if (slotBuilder.Count != 0) { Split(); ref LocalState stateToUpdate = ref whenTrue ? ref this.StateWhenTrue : ref this.StateWhenFalse; MarkSlotsAsNotNull(slotBuilder, ref stateToUpdate); } slotBuilder.Free(); } protected override bool VisitInterpolatedStringHandlerParts(BoundInterpolatedStringBase node, bool usesBoolReturns, bool firstPartIsConditional, ref LocalState shortCircuitState) { var result = base.VisitInterpolatedStringHandlerParts(node, usesBoolReturns, firstPartIsConditional, ref shortCircuitState); SetNotNullResult(node); return result; } protected override void VisitInterpolatedStringBinaryOperatorNode(BoundBinaryOperator node) { SetNotNullResult(node); } /// <summary> /// If we learn that the operand is non-null, we can infer that certain /// sub-expressions were also non-null. /// Get all nested conditional slots for those sub-expressions. For example in a?.b?.c we'll set a, b, and c. /// Only returns slots for tracked expressions. /// </summary> /// <remarks>https://github.com/dotnet/roslyn/issues/53397 This method should potentially be removed.</remarks> private void GetSlotsToMarkAsNotNullable(BoundExpression operand, ArrayBuilder<int> slotBuilder) { Debug.Assert(operand != null); var previousConditionalAccessSlot = _lastConditionalAccessSlot; try { while (true) { // Due to the nature of binding, if there are conditional access they will be at the top of the bound tree, // potentially with a conversion on top of it. We go through any conditional accesses, adding slots for the // conditional receivers if they have them. If we ever get to a receiver that MakeSlot doesn't return a slot // for, nothing underneath is trackable and we bail at that point. Example: // // a?.GetB()?.C // a is a field, GetB is a method, and C is a property // // The top of the tree is the a?.GetB() conditional call. We'll ask for a slot for a, and we'll get one because // fields have slots. The AccessExpression of the BoundConditionalAccess is another BoundConditionalAccess, this time // with a receiver of the GetB() BoundCall. Attempting to get a slot for this receiver will fail, and we'll // return an array with just the slot for a. int slot; switch (operand.Kind) { case BoundKind.Conversion: // https://github.com/dotnet/roslyn/issues/33879 Detect when conversion has a nullable operand operand = ((BoundConversion)operand).Operand; continue; case BoundKind.AsOperator: operand = ((BoundAsOperator)operand).Operand; continue; case BoundKind.ConditionalAccess: var conditional = (BoundConditionalAccess)operand; GetSlotsToMarkAsNotNullable(conditional.Receiver, slotBuilder); slot = MakeSlot(conditional.Receiver); if (slot > 0) { // We need to continue the walk regardless of whether the receiver should be updated. var receiverType = conditional.Receiver.Type!; if (receiverType.IsNullableType()) slot = GetNullableOfTValueSlot(receiverType, slot, out _); } if (slot > 0) { // When MakeSlot is called on the nested AccessExpression, it will recurse through receivers // until it gets to the BoundConditionalReceiver associated with this node. In our override // of MakeSlot, we substitute this slot when we encounter a BoundConditionalReceiver, and reset the // _lastConditionalAccess field. _lastConditionalAccessSlot = slot; operand = conditional.AccessExpression; continue; } // If there's no slot for this receiver, there cannot be another slot for any of the remaining // access expressions. break; default: // Attempt to create a slot for the current thing. If there were any more conditional accesses, // they would have been on top, so this is the last thing we need to specially handle. // https://github.com/dotnet/roslyn/issues/33879 When we handle unconditional access survival (ie after // c.D has been invoked, c must be nonnull or we've thrown a NullRef), revisit whether // we need more special handling here slot = MakeSlot(operand); if (slot > 0 && PossiblyNullableType(operand.Type)) { slotBuilder.Add(slot); } break; } return; } } finally { _lastConditionalAccessSlot = previousConditionalAccessSlot; } } private static bool PossiblyNullableType([NotNullWhen(true)] TypeSymbol? operandType) => operandType?.CanContainNull() == true; private static void MarkSlotsAsNotNull(ArrayBuilder<int> slots, ref LocalState stateToUpdate) { foreach (int slot in slots) { stateToUpdate[slot] = NullableFlowState.NotNull; } } private void LearnFromNonNullTest(BoundExpression expression, ref LocalState state) { if (expression is BoundValuePlaceholderBase placeholder) { if (_resultForPlaceholdersOpt != null && _resultForPlaceholdersOpt.TryGetValue(placeholder, out var value) && value.Replacement != null) { expression = value.Replacement; } else { AssertPlaceholderAllowedWithoutRegistration(placeholder); return; } } var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(expression, slotBuilder); MarkSlotsAsNotNull(slotBuilder, ref state); slotBuilder.Free(); } private void LearnFromNonNullTest(int slot, ref LocalState state) { state[slot] = NullableFlowState.NotNull; } private void LearnFromNullTest(BoundExpression expression, ref LocalState state) { // nothing to learn about a constant if (expression.ConstantValue != null) return; // We should not blindly strip conversions here. Tracked by https://github.com/dotnet/roslyn/issues/36164 var expressionWithoutConversion = RemoveConversion(expression, includeExplicitConversions: true).expression; var slot = MakeSlot(expressionWithoutConversion); // Since we know for sure the slot is null (we just tested it), we know that dependent slots are not // reachable and therefore can be treated as not null. However, we have not computed the proper // (inferred) type for the expression, so we cannot compute the correct symbols for the member slots here // (using the incorrect symbols would result in computing an incorrect default state for them). // Therefore we do not mark dependent slots not null. See https://github.com/dotnet/roslyn/issues/39624 LearnFromNullTest(slot, expressionWithoutConversion.Type, ref state, markDependentSlotsNotNull: false); } private void LearnFromNullTest(int slot, TypeSymbol? expressionType, ref LocalState state, bool markDependentSlotsNotNull) { if (slot > 0 && PossiblyNullableType(expressionType)) { if (state[slot] == NullableFlowState.NotNull) { // Note: We leave a MaybeDefault state as-is state[slot] = NullableFlowState.MaybeNull; } if (markDependentSlotsNotNull) { MarkDependentSlotsNotNull(slot, expressionType, ref state); } } } // If we know for sure that a slot contains a null value, then we know for sure that dependent slots // are "unreachable" so we might as well treat them as not null. That way when this state is merged // with another state, those dependent states won't pollute values from the other state. private void MarkDependentSlotsNotNull(int slot, TypeSymbol expressionType, ref LocalState state, int depth = 2) { if (depth <= 0) return; foreach (var member in getMembers(expressionType)) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var containingType = this._symbol?.ContainingType; if ((member is PropertySymbol { IsIndexedProperty: false } || member.Kind == SymbolKind.Field) && member.RequiresInstanceReceiver() && (containingType is null || AccessCheck.IsSymbolAccessible(member, containingType, ref discardedUseSiteInfo))) { int childSlot = GetOrCreateSlot(member, slot, forceSlotEvenIfEmpty: true, createIfMissing: false); if (childSlot > 0) { state[childSlot] = NullableFlowState.NotNull; MarkDependentSlotsNotNull(childSlot, member.GetTypeOrReturnType().Type, ref state, depth - 1); } } } static IEnumerable<Symbol> getMembers(TypeSymbol type) { // First, return the direct members foreach (var member in type.GetMembers()) yield return member; // All types inherit members from their effective bases for (NamedTypeSymbol baseType = effectiveBase(type); !(baseType is null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) foreach (var member in baseType.GetMembers()) yield return member; // Interfaces and type parameters inherit from their effective interfaces foreach (NamedTypeSymbol interfaceType in inheritedInterfaces(type)) foreach (var member in interfaceType.GetMembers()) yield return member; yield break; static NamedTypeSymbol effectiveBase(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.EffectiveBaseClassNoUseSiteDiagnostics, var t => t.BaseTypeNoUseSiteDiagnostics, }; static ImmutableArray<NamedTypeSymbol> inheritedInterfaces(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.AllEffectiveInterfacesNoUseSiteDiagnostics, { TypeKind: TypeKind.Interface } => type.AllInterfacesNoUseSiteDiagnostics, _ => ImmutableArray<NamedTypeSymbol>.Empty, }; } } private static BoundExpression SkipReferenceConversions(BoundExpression possiblyConversion) { while (possiblyConversion.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)possiblyConversion; switch (conversion.ConversionKind) { case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: possiblyConversion = conversion.Operand; break; default: return possiblyConversion; } } return possiblyConversion; } public override BoundNode? VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; int leftSlot = MakeSlot(leftOperand); TypeWithAnnotations targetType = VisitLvalueWithAnnotations(leftOperand); var leftState = this.State.Clone(); LearnFromNonNullTest(leftOperand, ref leftState); LearnFromNullTest(leftOperand, ref this.State); if (node.IsNullableValueTypeAssignment) { targetType = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); } TypeWithState rightResult = VisitOptionalImplicitConversion(rightOperand, targetType, useLegacyWarnings: UseLegacyWarnings(leftOperand, targetType), trackMembers: false, AssignmentKind.Assignment); TrackNullableStateForAssignment(rightOperand, targetType, leftSlot, rightResult, MakeSlot(rightOperand)); Join(ref this.State, ref leftState); TypeWithState resultType = TypeWithState.Create(targetType.Type, rightResult.State); SetResultType(node, resultType); return null; } public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { Debug.Assert(!IsConditionalState); BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; if (IsConstantNull(leftOperand)) { VisitRvalue(leftOperand); Visit(rightOperand); var rightUnconditionalResult = ResultType; // Should be able to use rightResult for the result of the operator but // binding may have generated a different result type in the case of errors. SetResultType(node, TypeWithState.Create(node.Type, rightUnconditionalResult.State)); return null; } VisitPossibleConditionalAccess(leftOperand, out var whenNotNull); TypeWithState leftResult = ResultType; Unsplit(); LearnFromNullTest(leftOperand, ref this.State); bool leftIsConstant = leftOperand.ConstantValue != null; if (leftIsConstant) { SetUnreachable(); } Visit(rightOperand); TypeWithState rightResult = ResultType; Join(ref whenNotNull); var leftResultType = leftResult.Type; var rightResultType = rightResult.Type; var (resultType, leftState) = node.OperatorResultKind switch { BoundNullCoalescingOperatorResultKind.NoCommonType => (node.Type, NullableFlowState.NotNull), BoundNullCoalescingOperatorResultKind.LeftType => getLeftResultType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedType => getLeftResultType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightType => getResultStateWithRightType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedRightType => getResultStateWithRightType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightDynamicType => (rightResultType!, NullableFlowState.NotNull), _ => throw ExceptionUtilities.UnexpectedValue(node.OperatorResultKind), }; SetResultType(node, TypeWithState.Create(resultType, rightResult.State.Join(leftState))); return null; (TypeSymbol ResultType, NullableFlowState LeftState) getLeftResultType(TypeSymbol leftType, TypeSymbol rightType) { Debug.Assert(rightType is object); // If there was an identity conversion between the two operands (in short, if there // is no implicit conversion on the right operand), then check nullable conversions // in both directions since it's possible the right operand is the better result type. if ((node.RightOperand as BoundConversion)?.ExplicitCastInCode != false && GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: false, isChecked: node.Checked) is { Exists: true } conversion) { Debug.Assert(!conversion.IsUserDefined); return (rightType, NullableFlowState.NotNull); } conversion = GenerateConversionForConditionalOperator(node.RightOperand, rightType, leftType, reportMismatch: true, isChecked: node.Checked); Debug.Assert(!conversion.IsUserDefined); return (leftType, NullableFlowState.NotNull); } (TypeSymbol ResultType, NullableFlowState LeftState) getResultStateWithRightType(TypeSymbol leftType, TypeSymbol rightType) { var conversion = GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: true, isChecked: node.Checked); if (conversion.IsUserDefined) { var conversionResult = VisitConversion( conversionOpt: null, node.LeftOperand, conversion, TypeWithAnnotations.Create(rightType), // When considering the conversion on the left node, it can only occur in the case where the underlying // execution returned non-null TypeWithState.Create(leftType, NullableFlowState.NotNull), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: false); Debug.Assert(conversionResult.Type is not null); return (conversionResult.Type!, conversionResult.State); } return (rightType, NullableFlowState.NotNull); } } /// <summary> /// Visits a node only if it is a conditional access. /// Returns 'true' if and only if the node was visited. /// </summary> private bool TryVisitConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { var (operand, conversion) = RemoveConversion(node, includeExplicitConversions: true); if (operand is not BoundConditionalAccess access || !CanPropagateStateWhenNotNull(conversion)) { stateWhenNotNull = default; return false; } Unsplit(); VisitConditionalAccess(access, out stateWhenNotNull); if (node is BoundConversion boundConversion) { var operandType = ResultType; TypeWithAnnotations explicitType = boundConversion.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(boundConversion.Type); Debug.Assert(targetType.HasType); var result = VisitConversion(boundConversion, access, conversion, targetType, operandType, checkConversion: true, fromExplicitCast, useLegacyWarnings: true, assignmentKind: AssignmentKind.Assignment); SetResultType(boundConversion, result); } Debug.Assert(!IsConditionalState); return true; } /// <summary> /// Unconditionally visits an expression and returns the "state when not null" for the expression. /// </summary> private bool VisitPossibleConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { if (TryVisitConditionalAccess(node, out stateWhenNotNull)) { return true; } // in case we *didn't* have a conditional access, the only thing we learn in the "state when not null" // is that the top-level expression was non-null. Visit(node); stateWhenNotNull = PossiblyConditionalState.Create(this); (node, _) = RemoveConversion(node, includeExplicitConversions: true); var slot = MakeSlot(node); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenTrue); LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenFalse); } else { LearnFromNonNullTest(slot, ref stateWhenNotNull.State); } } return false; } private void VisitConditionalAccess(BoundConditionalAccess node, out PossiblyConditionalState stateWhenNotNull) { Debug.Assert(!IsConditionalState); var receiver = node.Receiver; // handle scenarios like `(a?.b)?.c()` VisitPossibleConditionalAccess(receiver, out stateWhenNotNull); Unsplit(); _currentConditionalReceiverVisitResult = _visitResult; var previousConditionalAccessSlot = _lastConditionalAccessSlot; if (receiver.ConstantValue is { IsNull: false }) { // Consider a scenario like `"a"?.M0(x = 1)?.M0(y = 1)`. // We can "know" that `.M0(x = 1)` was evaluated unconditionally but not `M0(y = 1)`. // Therefore we do a VisitPossibleConditionalAccess here which unconditionally includes the "after receiver" state in State // and includes the "after subsequent conditional accesses" in stateWhenNotNull VisitPossibleConditionalAccess(node.AccessExpression, out stateWhenNotNull); } else { var savedState = this.State.Clone(); if (IsConstantNull(receiver)) { SetUnreachable(); _lastConditionalAccessSlot = -1; } else { // In the when-null branch, the receiver is known to be maybe-null. // In the other branch, the receiver is known to be non-null. LearnFromNullTest(receiver, ref savedState); makeAndAdjustReceiverSlot(receiver); SetPossiblyConditionalState(stateWhenNotNull); } // We want to preserve stateWhenNotNull from accesses in the same "chain": // a?.b(out x)?.c(out y); // expected to preserve stateWhenNotNull from both ?.b(out x) and ?.c(out y) // but not accesses in nested expressions: // a?.b(out x, c?.d(out y)); // expected to preserve stateWhenNotNull from a?.b(out x, ...) but not from c?.d(out y) BoundExpression expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // we assume that non-conditional accesses can never contain conditional accesses from the same "chain". // that is, we never have to dig through non-conditional accesses to find and handle conditional accesses. Debug.Assert(innerCondAccess.Receiver is not (BoundConditionalAccess or BoundConversion)); VisitRvalue(innerCondAccess.Receiver); _currentConditionalReceiverVisitResult = _visitResult; makeAndAdjustReceiverSlot(innerCondAccess.Receiver); // The savedState here represents the scenario where 0 or more of the access expressions could have been evaluated. // e.g. after visiting `a?.b(x = null)?.c(x = new object())`, the "state when not null" of `x` is NotNull, but the "state when maybe null" of `x` is MaybeNull. Join(ref savedState, ref State); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); Visit(expr); expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // The resulting nullability of each nested conditional access is the same as the resulting nullability of the rightmost access. SetAnalyzedNullability(innerCondAccess, _visitResult); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); var slot = MakeSlot(expr); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref StateWhenTrue); LearnFromNonNullTest(slot, ref StateWhenFalse); } else { LearnFromNonNullTest(slot, ref State); } } stateWhenNotNull = PossiblyConditionalState.Create(this); Unsplit(); Join(ref this.State, ref savedState); } var accessTypeWithAnnotations = LvalueResultType; TypeSymbol accessType = accessTypeWithAnnotations.Type; var oldType = node.Type; var resultType = oldType.IsVoidType() || oldType.IsErrorType() ? oldType : oldType.IsNullableType() && !accessType.IsNullableType() ? MakeNullableOf(accessTypeWithAnnotations) : accessType; // Per LDM 2019-02-13 decision, the result of a conditional access "may be null" even if // both the receiver and right-hand-side are believed not to be null. SetResultType(node, TypeWithState.Create(resultType, NullableFlowState.MaybeDefault)); _currentConditionalReceiverVisitResult = default; _lastConditionalAccessSlot = previousConditionalAccessSlot; void makeAndAdjustReceiverSlot(BoundExpression receiver) { var slot = MakeSlot(receiver); if (slot > -1) LearnFromNonNullTest(slot, ref State); // given `a?.b()`, when `a` is a nullable value type, // the conditional receiver for `?.b()` must be linked to `a.Value`, not to `a`. if (slot > 0 && receiver.Type?.IsNullableType() == true) slot = GetNullableOfTValueSlot(receiver.Type, slot, out _); _lastConditionalAccessSlot = slot; } } public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) { VisitConditionalAccess(node, out _); return null; } protected override BoundNode? VisitConditionalOperatorCore( BoundExpression node, bool isRef, BoundExpression condition, BoundExpression originalConsequence, BoundExpression originalAlternative) { VisitCondition(condition); var consequenceState = this.StateWhenTrue; var alternativeState = this.StateWhenFalse; TypeWithState consequenceRValue; TypeWithState alternativeRValue; if (isRef) { TypeWithAnnotations consequenceLValue; TypeWithAnnotations alternativeLValue; (consequenceLValue, consequenceRValue) = visitConditionalRefOperand(consequenceState, originalConsequence); consequenceState = this.State; (alternativeLValue, alternativeRValue) = visitConditionalRefOperand(alternativeState, originalAlternative); Join(ref this.State, ref consequenceState); TypeSymbol? refResultType = node.Type?.SetUnknownNullabilityForReferenceTypes(); if (IsNullabilityMismatch(consequenceLValue, alternativeLValue)) { // l-value types must match ReportNullabilityMismatchInAssignment(node.Syntax, consequenceLValue, alternativeLValue); } else if (!node.HasErrors) { refResultType = consequenceRValue.Type!.MergeEquivalentTypes(alternativeRValue.Type, VarianceKind.None); } var lValueAnnotation = consequenceLValue.NullableAnnotation.EnsureCompatible(alternativeLValue.NullableAnnotation); var rValueState = consequenceRValue.State.Join(alternativeRValue.State); SetResult(node, TypeWithState.Create(refResultType, rValueState), TypeWithAnnotations.Create(refResultType, lValueAnnotation)); return null; } (var consequence, var consequenceConversion, consequenceRValue) = visitConditionalOperand(consequenceState, originalConsequence); var consequenceConditionalState = PossiblyConditionalState.Create(this); consequenceState = CloneAndUnsplit(ref consequenceConditionalState); var consequenceEndReachable = consequenceState.Reachable; (var alternative, var alternativeConversion, alternativeRValue) = visitConditionalOperand(alternativeState, originalAlternative); var alternativeConditionalState = PossiblyConditionalState.Create(this); alternativeState = CloneAndUnsplit(ref alternativeConditionalState); var alternativeEndReachable = alternativeState.Reachable; SetPossiblyConditionalState(in consequenceConditionalState); Join(ref alternativeConditionalState); TypeSymbol? resultType; bool wasTargetTyped = node is BoundConditionalOperator { WasTargetTyped: true }; if (node.HasErrors || wasTargetTyped) { resultType = null; } else { // Determine nested nullability using BestTypeInferrer. // If a branch is unreachable, we could use the nested nullability of the other // branch, but that requires using the nullability of the branch as it applies to the // target type. For instance, the result of the conditional in the following should // be `IEnumerable<object>` not `object[]`: // object[] a = ...; // IEnumerable<object?> b = ...; // var c = true ? a : b; BoundExpression consequencePlaceholder = CreatePlaceholderIfNecessary(consequence, consequenceRValue.ToTypeWithAnnotations(compilation)); BoundExpression alternativePlaceholder = CreatePlaceholderIfNecessary(alternative, alternativeRValue.ToTypeWithAnnotations(compilation)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; resultType = BestTypeInferrer.InferBestTypeForConditionalOperator(consequencePlaceholder, alternativePlaceholder, _conversions, out _, ref discardedUseSiteInfo); } resultType ??= node.Type?.SetUnknownNullabilityForReferenceTypes(); TypeWithAnnotations resultTypeWithAnnotations; if (resultType is null) { if (!wasTargetTyped) { // This can happen when we're inferring the return type of a lambda. For this case, we don't need to do any work, // the unconverted conditional operator can't contribute info. The conversion that should be on top of this // can add or remove nullability, and nested nodes aren't being publicly exposed by the semantic model. Debug.Assert(node is BoundUnconvertedConditionalOperator); Debug.Assert(_returnTypesOpt is not null); SetResultType(node, TypeWithState.Create(resultType, default)); return null; } resultTypeWithAnnotations = default; } else { resultTypeWithAnnotations = TypeWithAnnotations.Create(resultType); } TypeWithState typeWithState = convertArms( node, originalConsequence, originalAlternative, consequenceState, alternativeState, consequenceRValue, alternativeRValue, consequence, consequenceConversion, consequenceEndReachable, alternative, alternativeConversion, alternativeEndReachable, resultTypeWithAnnotations, wasTargetTyped); SetResultType(node, typeWithState, updateAnalyzedNullability: false); return null; TypeWithState convertArms( BoundExpression node, BoundExpression originalConsequence, BoundExpression originalAlternative, LocalState consequenceState, LocalState alternativeState, TypeWithState consequenceRValue, TypeWithState alternativeRValue, BoundExpression consequence, Conversion consequenceConversion, bool consequenceEndReachable, BoundExpression alternative, Conversion alternativeConversion, bool alternativeEndReachable, TypeWithAnnotations resultTypeWithAnnotations, bool wasTargetTyped) { NullableFlowState resultState; if (!wasTargetTyped) { TypeWithState convertedConsequenceResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalConsequence, consequence, consequenceConversion, resultTypeWithAnnotations, consequenceRValue, consequenceState, consequenceEndReachable); TypeWithState convertedAlternativeResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalAlternative, alternative, alternativeConversion, resultTypeWithAnnotations, alternativeRValue, alternativeState, alternativeEndReachable); resultState = convertedConsequenceResult.State.Join(convertedAlternativeResult.State); var typeWithState = TypeWithState.Create(resultTypeWithAnnotations.Type, resultState); SetAnalyzedNullability(node, typeWithState); return typeWithState; } else { addConvertArmsAsCompletion( node, originalConsequence, originalAlternative, consequenceState, alternativeState, consequenceRValue, alternativeRValue, consequence, consequenceConversion, consequenceEndReachable, alternative, alternativeConversion, alternativeEndReachable); resultState = consequenceRValue.State.Join(alternativeRValue.State); return TypeWithState.Create(resultTypeWithAnnotations.Type, resultState); } } void addConvertArmsAsCompletion( BoundExpression node, BoundExpression originalConsequence, BoundExpression originalAlternative, LocalState consequenceState, LocalState alternativeState, TypeWithState consequenceRValue, TypeWithState alternativeRValue, BoundExpression consequence, Conversion consequenceConversion, bool consequenceEndReachable, BoundExpression alternative, Conversion alternativeConversion, bool alternativeEndReachable) { TargetTypedAnalysisCompletion[node] = (TypeWithAnnotations resultTypeWithAnnotations) => { return convertArms( node, originalConsequence, originalAlternative, consequenceState, alternativeState, consequenceRValue, alternativeRValue, consequence, consequenceConversion, consequenceEndReachable, alternative, alternativeConversion, alternativeEndReachable, resultTypeWithAnnotations, wasTargetTyped: false); }; } (BoundExpression, Conversion, TypeWithState) visitConditionalOperand(LocalState state, BoundExpression operand) { Conversion conversion; SetState(state); Debug.Assert(!isRef); BoundExpression operandNoConversion; (operandNoConversion, conversion) = RemoveConversion(operand, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(operand, operandNoConversion); Visit(operandNoConversion); return (operandNoConversion, conversion, ResultType); } (TypeWithAnnotations LValueType, TypeWithState RValueType) visitConditionalRefOperand(LocalState state, BoundExpression operand) { SetState(state); Debug.Assert(isRef); TypeWithAnnotations lValueType = VisitLvalueWithAnnotations(operand); return (lValueType, ResultType); } } private TypeWithState ConvertConditionalOperandOrSwitchExpressionArmResult( BoundExpression node, BoundExpression operand, Conversion conversion, TypeWithAnnotations targetType, TypeWithState operandType, LocalState state, bool isReachable) { var savedState = this.State; this.State = state; bool previousDisabledDiagnostics = _disableDiagnostics; // If the node is not reachable, then we're only visiting to get // nullability information for the public API, and not to produce diagnostics. // Disable diagnostics, and return default for the resulting state // to indicate that warnings were suppressed. if (!isReachable) { _disableDiagnostics = true; } var resultType = VisitConversion( GetConversionIfApplicable(node, operand), operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false); if (!isReachable) { resultType = default; _disableDiagnostics = previousDisabledDiagnostics; } this.State = savedState; return resultType; } private bool IsReachable() => this.IsConditionalState ? (this.StateWhenTrue.Reachable || this.StateWhenFalse.Reachable) : this.State.Reachable; /// <summary> /// Placeholders are bound expressions with type and state. /// But for typeless expressions (such as `null` or `(null, null)` we hold onto the original bound expression, /// as it will be useful for conversions from expression. /// </summary> private static BoundExpression CreatePlaceholderIfNecessary(BoundExpression expr, TypeWithAnnotations type) { return !type.HasType ? expr : new BoundExpressionWithNullability(expr.Syntax, expr, type.NullableAnnotation, type.Type); } public override BoundNode? VisitConditionalReceiver(BoundConditionalReceiver node) { var rvalueType = _currentConditionalReceiverVisitResult.RValueType.Type; if (rvalueType?.IsNullableType() == true) { rvalueType = rvalueType.GetNullableUnderlyingType(); } SetResultType(node, TypeWithState.Create(rvalueType, NullableFlowState.NotNull)); return null; } public override BoundNode? VisitCall(BoundCall node) { // Note: we analyze even omitted calls TypeWithState receiverType = VisitCallReceiver(node); ReinferMethodAndVisitArguments(node, receiverType); return null; } private void ReinferMethodAndVisitArguments(BoundCall node, TypeWithState receiverType) { var method = node.Method; ImmutableArray<RefKind> refKindsOpt = node.ArgumentRefKindsOpt; if (!receiverType.HasNullType) { // Update method based on inferred receiver type. method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } ImmutableArray<VisitArgumentResult> results; bool returnNotNull; (method, results, returnNotNull) = VisitArguments(node, node.Arguments, refKindsOpt, method!.Parameters, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod, method); ApplyMemberPostConditions(node.ReceiverOpt, method); LearnFromEqualsMethod(method, node, receiverType, results); var returnState = GetReturnTypeWithState(method); if (returnNotNull) { returnState = returnState.WithNotNullState(); } SetResult(node, returnState, method.ReturnTypeWithAnnotations); SetUpdatedSymbol(node, node.Method, method); } private void LearnFromEqualsMethod(MethodSymbol method, BoundCall node, TypeWithState receiverType, ImmutableArray<VisitArgumentResult> results) { // easy out var parameterCount = method.ParameterCount; var arguments = node.Arguments; if (node.HasErrors || (parameterCount != 1 && parameterCount != 2) || parameterCount != arguments.Length || method.MethodKind != MethodKind.Ordinary || method.ReturnType.SpecialType != SpecialType.System_Boolean || (method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__Equals).Name && method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__ReferenceEquals).Name && !anyOverriddenMethodHasExplicitImplementation(method))) { return; } var isStaticEqualsMethod = method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__EqualsObjectObject)) || method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__ReferenceEquals)); if (isStaticEqualsMethod || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_Collections_Generic_IEqualityComparer_T__Equals)) { Debug.Assert(arguments.Length == 2); learnFromEqualsMethodArguments(arguments[0], results[0].RValueType, arguments[1], results[1].RValueType); return; } var isObjectEqualsMethodOrOverride = method.GetLeastOverriddenMethod(accessingTypeOpt: null) .Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__Equals)); if (node.ReceiverOpt is BoundExpression receiver && (isObjectEqualsMethodOrOverride || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_IEquatable_T__Equals))) { Debug.Assert(arguments.Length == 1); learnFromEqualsMethodArguments(receiver, receiverType, arguments[0], results[0].RValueType); return; } static bool anyOverriddenMethodHasExplicitImplementation(MethodSymbol method) { for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.IsExplicitInterfaceImplementation) { return true; } } return false; } static bool isWellKnownEqualityMethodOrImplementation(CSharpCompilation compilation, MethodSymbol method, TypeSymbol? receiverType, WellKnownMember wellKnownMember) { var wellKnownMethod = (MethodSymbol?)compilation.GetWellKnownTypeMember(wellKnownMember); if (wellKnownMethod is null || receiverType is null) { return false; } var wellKnownType = wellKnownMethod.ContainingType; var parameterType = method.Parameters[0].TypeWithAnnotations; var constructedType = wellKnownType.Construct(ImmutableArray.Create(parameterType)); var constructedMethod = wellKnownMethod.AsMember(constructedType); // FindImplementationForInterfaceMember doesn't check if this method is itself the interface method we're looking for if (constructedMethod.Equals(method)) { return true; } // check whether 'method', when called on this receiver, is an implementation of 'constructedMethod'. for (var baseType = receiverType; baseType is object && method is object; baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var implementationMethod = baseType.FindImplementationForInterfaceMember(constructedMethod); if (implementationMethod is null) { // we know no base type will implement this interface member either return false; } if (implementationMethod.ContainingType.IsInterface) { // this method cannot be called directly from source because an interface can only explicitly implement a method from its base interface. return false; } // could be calling an override of a method that implements the interface method for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.Equals(implementationMethod)) { return true; } } // the Equals method being called isn't the method that implements the interface method in this type. // it could be a method that implements the interface on a base type, so check again with the base type of 'implementationMethod.ContainingType' // e.g. in this hierarchy: // class A -> B -> C -> D // method virtual B.Equals -> override D.Equals // // we would potentially check: // 1. D.Equals when called on D, then B.Equals when called on D // 2. B.Equals when called on C // 3. B.Equals when called on B // 4. give up when checking A, since B.Equals is not overriding anything in A // we know that implementationMethod.ContainingType is the same type or a base type of 'baseType', // and that the implementation method will be the same between 'baseType' and 'implementationMethod.ContainingType'. // we step through the intermediate bases in order to skip unnecessary override methods. while (!baseType.Equals(implementationMethod.ContainingType) && method is object) { if (baseType.Equals(method.ContainingType)) { // since we're about to move on to the base of 'method.ContainingType', // we know the implementation could only be an overridden method of 'method'. method = method.OverriddenMethod; } baseType = baseType.BaseTypeNoUseSiteDiagnostics; // the implementation method must be contained in this 'baseType' or one of its bases. Debug.Assert(baseType is object); } // now 'baseType == implementationMethod.ContainingType', so if 'method' is // contained in that same type we should advance 'method' one more time. if (method is object && baseType.Equals(method.ContainingType)) { method = method.OverriddenMethod; } } return false; } void learnFromEqualsMethodArguments(BoundExpression left, TypeWithState leftType, BoundExpression right, TypeWithState rightType) { // comparing anything to a null literal gives maybe-null when true and not-null when false // comparing a maybe-null to a not-null gives us not-null when true, nothing learned when false if (left.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(right, ref StateWhenTrue); LearnFromNonNullTest(right, ref StateWhenFalse); } else if (right.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(left, ref StateWhenTrue); LearnFromNonNullTest(left, ref StateWhenFalse); } else if (leftType.MayBeNull && rightType.IsNotNull) { Split(); LearnFromNonNullTest(left, ref StateWhenTrue); } else if (rightType.MayBeNull && leftType.IsNotNull) { Split(); LearnFromNonNullTest(right, ref StateWhenTrue); } } } private bool IsCompareExchangeMethod(MethodSymbol? method) { if (method is null) { return false; } return method.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange), SymbolEqualityComparer.ConsiderEverything.CompareKind) || method.OriginalDefinition.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T), SymbolEqualityComparer.ConsiderEverything.CompareKind); } private readonly struct CompareExchangeInfo { public readonly ImmutableArray<BoundExpression> Arguments; public readonly ImmutableArray<VisitArgumentResult> Results; public readonly ImmutableArray<int> ArgsToParamsOpt; public CompareExchangeInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> results, ImmutableArray<int> argsToParamsOpt) { Arguments = arguments; Results = results; ArgsToParamsOpt = argsToParamsOpt; } public bool IsDefault => Arguments.IsDefault || Results.IsDefault; } private NullableFlowState LearnFromCompareExchangeMethod(in CompareExchangeInfo compareExchangeInfo) { Debug.Assert(!compareExchangeInfo.IsDefault); // In general a call to CompareExchange of the form: // // Interlocked.CompareExchange(ref location, value, comparand); // // will be analyzed similarly to the following: // // if (location == comparand) // { // location = value; // } if (compareExchangeInfo.Arguments.Length != 3) { // This can occur if CompareExchange has optional arguments. // Since none of the main runtimes have optional arguments, // we bail to avoid an exception but don't bother actually calculating the FlowState. return NullableFlowState.NotNull; } var argsToParamsOpt = compareExchangeInfo.ArgsToParamsOpt; Debug.Assert(argsToParamsOpt is { IsDefault: true } or { Length: 3 }); var (comparandIndex, valueIndex, locationIndex) = argsToParamsOpt.IsDefault ? (2, 1, 0) : (argsToParamsOpt.IndexOf(2), argsToParamsOpt.IndexOf(1), argsToParamsOpt.IndexOf(0)); var comparand = compareExchangeInfo.Arguments[comparandIndex]; var valueFlowState = compareExchangeInfo.Results[valueIndex].RValueType.State; if (comparand.ConstantValue?.IsNull == true) { // If location contained a null, then the write `location = value` definitely occurred } else { var locationFlowState = compareExchangeInfo.Results[locationIndex].RValueType.State; // A write may have occurred valueFlowState = valueFlowState.Join(locationFlowState); } return valueFlowState; } private TypeWithState VisitCallReceiver(BoundCall node) { var receiverOpt = node.ReceiverOpt; TypeWithState receiverType = default; if (receiverOpt != null) { receiverType = VisitRvalueWithState(receiverOpt); // methods which are members of Nullable<T> (ex: ToString, GetHashCode) can be invoked on null receiver. // However, inherited methods (ex: GetType) are invoked on a boxed value (since base types are reference types) // and therefore in those cases nullable receivers should be checked for nullness. bool checkNullableValueType = false; var type = receiverType.Type; var method = node.Method; if (method.RequiresInstanceReceiver && type?.IsNullableType() == true && method.ContainingType.IsReferenceType) { checkNullableValueType = true; } else if (method.OriginalDefinition == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { // call to get_Value may not occur directly in source, but may be inserted as a result of premature lowering. // One example where we do it is foreach with nullables. // The reason is Dev10 compatibility (see: UnwrapCollectionExpressionIfNullable in ForEachLoopBinder.cs) // Regardless of the reasons, we know that the method does not tolerate nulls. checkNullableValueType = true; } // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType); } return receiverType; } private TypeWithState GetReturnTypeWithState(MethodSymbol method) { return TypeWithState.Create(method.ReturnTypeWithAnnotations, GetRValueAnnotations(method)); } private FlowAnalysisAnnotations GetRValueAnnotations(Symbol? symbol) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = symbol.GetFlowAnalysisAnnotations(); return annotations & (FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull); } private FlowAnalysisAnnotations GetParameterAnnotations(ParameterSymbol parameter) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) return IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : parameter.FlowAnalysisAnnotations; } /// <summary> /// Fix a TypeWithAnnotations based on Allow/DisallowNull annotations prior to a conversion or assignment. /// Note this does not work for nullable value types, so an additional check with <see cref="CheckDisallowedNullAssignment"/> may be required. /// </summary> private static TypeWithAnnotations ApplyLValueAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations flowAnalysisAnnotations) { if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.DisallowNull) == FlowAnalysisAnnotations.DisallowNull) { return declaredType.AsNotAnnotated(); } else if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.AllowNull) == FlowAnalysisAnnotations.AllowNull) { return declaredType.AsAnnotated(); } return declaredType; } /// <summary> /// Update the null-state based on MaybeNull/NotNull /// </summary> private static TypeWithState ApplyUnconditionalAnnotations(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } return typeWithState; } private static TypeWithAnnotations ApplyUnconditionalAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return declaredType.AsAnnotated(); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return declaredType.AsNotAnnotated(); } return declaredType; } // https://github.com/dotnet/roslyn/issues/29863 Record in the node whether type // arguments were implicit, to allow for cases where the syntax is not an // invocation (such as a synthesized call from a query interpretation). private static bool HasImplicitTypeArguments(BoundNode node) { if (node is BoundCollectionElementInitializer { AddMethod: { TypeArgumentsWithAnnotations: { IsEmpty: false } } }) { return true; } if (node is BoundForEachStatement { EnumeratorInfoOpt: { GetEnumeratorInfo: { Method: { TypeArgumentsWithAnnotations: { IsEmpty: false } } } } }) { return true; } var syntax = node.Syntax; if (syntax.Kind() != SyntaxKind.InvocationExpression) { // Unexpected syntax kind. return false; } return HasImplicitTypeArguments(((InvocationExpressionSyntax)syntax).Expression); } private static bool HasImplicitTypeArguments(SyntaxNode syntax) { var nameSyntax = Binder.GetNameSyntax(syntax, out _); if (nameSyntax == null) { // Unexpected syntax kind. return false; } nameSyntax = nameSyntax.GetUnqualifiedName(); return nameSyntax.Kind() != SyntaxKind.GenericName; } protected override void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { // Callers should be using VisitArguments overload below. throw ExceptionUtilities.Unreachable; } private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol? method, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod) { return VisitArguments(node, arguments, refKindsOpt, method is null ? default : method.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method); } private ImmutableArray<VisitArgumentResult> VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, PropertySymbol? property, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { return VisitArguments(node, arguments, refKindsOpt, property is null ? default : property.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod: false).results; } /// <summary> /// If you pass in a method symbol, its type arguments will be re-inferred and the re-inferred method will be returned. /// </summary> private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method = null) { var result = VisitArguments(node, arguments, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method, delayCompletionForTargetMember: false); Debug.Assert(result.completion is null); return (result.method, result.results, result.returnNotNull); } private delegate (MethodSymbol? method, bool returnNotNull) ArgumentsCompletionDelegate(ImmutableArray<VisitArgumentResult> argumentResults, ImmutableArray<ParameterSymbol> parametersOpt, MethodSymbol? method); private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull, ArgumentsCompletionDelegate? completion) VisitArguments( BoundNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method, bool delayCompletionForTargetMember) { Debug.Assert(!arguments.IsDefault); (ImmutableArray<BoundExpression> argumentsNoConversions, ImmutableArray<Conversion> conversions) = RemoveArgumentConversions(arguments, refKindsOpt); // Visit the arguments and collect results ImmutableArray<VisitArgumentResult> results = VisitArgumentsEvaluate(argumentsNoConversions, refKindsOpt, GetParametersAnnotations(arguments, parametersOpt, argsToParamsOpt, expanded), defaultArguments); return visitArguments( node, arguments, argumentsNoConversions, conversions, results, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method, delayCompletionForTargetMember); (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull, ArgumentsCompletionDelegate? completion) visitArguments( BoundNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<BoundExpression> argumentsNoConversions, ImmutableArray<Conversion> conversions, ImmutableArray<VisitArgumentResult> results, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method, bool delayCompletionForTargetMember) { bool shouldReturnNotNull = false; if (delayCompletionForTargetMember) { return (method, results, shouldReturnNotNull, visitArgumentsAsContinuation( node, arguments, argumentsNoConversions, conversions, refKindsOpt, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod)); } // Re-infer method type parameters if (method?.IsGenericMethod == true) { if (HasImplicitTypeArguments(node)) { method = InferMethodTypeArguments(method, GetArgumentsForMethodTypeInference(results, argumentsNoConversions), refKindsOpt, argsToParamsOpt, expanded); parametersOpt = method.Parameters; } if (ConstraintsHelper.RequiresChecking(method)) { var syntax = node.Syntax; CheckMethodConstraints( syntax switch { InvocationExpressionSyntax { Expression: var expression } => expression, ForEachStatementSyntax { Expression: var expression } => expression, _ => syntax }, method); } } bool parameterHasNotNullIfNotNull = !IsAnalyzingAttribute && !parametersOpt.IsDefault && parametersOpt.Any(static p => !p.NotNullIfParameterNotNull.IsEmpty); var notNullParametersBuilder = parameterHasNotNullIfNotNull ? ArrayBuilder<ParameterSymbol>.GetInstance() : null; var conversionResultsBuilder = ArrayBuilder<VisitResult>.GetInstance(results.Length); if (!parametersOpt.IsDefault) { // Visit conversions, inbound assignments including pre-conditions ImmutableHashSet<string>? returnNotNullIfParameterNotNull = IsAnalyzingAttribute ? null : method?.ReturnNotNullIfParameterNotNull; for (int i = 0; i < results.Length; i++) { var argumentNoConversion = argumentsNoConversions[i]; var argument = i < arguments.Length ? arguments[i] : argumentNoConversion; if (argument is not BoundConversion && argumentNoConversion is BoundLambda lambda) { Debug.Assert(node.HasErrors); Debug.Assert((object)argument == argumentNoConversion); // 'VisitConversion' only visits a lambda when the lambda has an AnonymousFunction conversion. // This lambda doesn't have a conversion, so we need to visit it here. VisitLambda(lambda, delegateTypeOpt: null, results[i].StateForLambda); continue; } (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, bool isExpandedParamsArgument) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { // If this assert fails, we are missing necessary info to visit the // conversion of a target typed construct. Debug.Assert(!IsTargetTypedExpression(argumentNoConversion) || _targetTypedAnalysisCompletionOpt?.ContainsKey(argumentNoConversion) is true); // If this assert fails, it means we failed to visit a lambda for error recovery above. Debug.Assert(argumentNoConversion is not BoundLambda); continue; } // We disable diagnostics when: // 1. the containing call has errors (to reduce cascading diagnostics) // 2. on implicit default arguments (since that's really only an issue with the declaration) var previousDisableDiagnostics = _disableDiagnostics; _disableDiagnostics |= node.HasErrors || defaultArguments[i]; VisitArgumentConversionAndInboundAssignmentsAndPreConditions( GetConversionIfApplicable(argument, argumentNoConversion), argumentNoConversion, conversions.IsDefault || i >= conversions.Length ? Conversion.Identity : conversions[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], conversionResultsBuilder, invokedAsExtensionMethod && i == 0); _disableDiagnostics = previousDisableDiagnostics; if (results[i].RValueType.IsNotNull || isExpandedParamsArgument) { notNullParametersBuilder?.Add(parameter); if (returnNotNullIfParameterNotNull?.Contains(parameter.Name) == true) { shouldReturnNotNull = true; } } } } conversionResultsBuilder.Free(); if (node is BoundCall { Method: { OriginalDefinition: LocalFunctionSymbol localFunction } }) { VisitLocalFunctionUse(localFunction); } if (!node.HasErrors && !parametersOpt.IsDefault) { // For CompareExchange method we need more context to determine the state of outbound assignment CompareExchangeInfo compareExchangeInfo = IsCompareExchangeMethod(method) ? new CompareExchangeInfo(arguments, results, argsToParamsOpt) : default; // Visit outbound assignments and post-conditions // Note: the state may get split in this step for (int i = 0; i < arguments.Length; i++) { (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { continue; } VisitArgumentOutboundAssignmentsAndPostConditions( arguments[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], notNullParametersBuilder, (!compareExchangeInfo.IsDefault && parameter.Ordinal == 0) ? compareExchangeInfo : default); } } else { for (int i = 0; i < arguments.Length; i++) { // We can hit this case when dynamic methods are involved, or when there are errors. In either case we have no information, // so just assume that the conversions have the same nullability as the underlying result var argument = arguments[i]; var result = results[i]; var argumentNoConversion = argumentsNoConversions[i]; TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState.Create(argument.Type, result.RValueType.State), argument as BoundConversion, argumentNoConversion); } } if (!IsAnalyzingAttribute && method is object && (method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) { SetUnreachable(); } notNullParametersBuilder?.Free(); return (method, results, shouldReturnNotNull, null); } ArgumentsCompletionDelegate visitArgumentsAsContinuation( BoundNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<BoundExpression> argumentsNoConversions, ImmutableArray<Conversion> conversions, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod) { return (ImmutableArray<VisitArgumentResult> results, ImmutableArray<ParameterSymbol> parametersOpt, MethodSymbol? method) => { var result = visitArguments( node, arguments, argumentsNoConversions, conversions, results, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method, delayCompletionForTargetMember: false); Debug.Assert(result.completion is null); return (result.method, result.returnNotNull); }; } } private void ApplyMemberPostConditions(BoundExpression? receiverOpt, MethodSymbol? method) { if (method is null) { return; } int receiverSlot = method.IsStatic ? 0 : receiverOpt is null ? -1 : MakeSlot(receiverOpt); if (receiverSlot < 0) { return; } ApplyMemberPostConditions(receiverSlot, method); } private void ApplyMemberPostConditions(int receiverSlot, MethodSymbol method) { Debug.Assert(receiverSlot >= 0); do { var type = method.ContainingType; var notNullMembers = method.NotNullMembers; var notNullWhenTrueMembers = method.NotNullWhenTrueMembers; var notNullWhenFalseMembers = method.NotNullWhenFalseMembers; if (IsConditionalState) { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenFalse); } else { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref State); } if (method.ReturnType.SpecialType == SpecialType.System_Boolean && !(notNullWhenTrueMembers.IsEmpty && notNullWhenFalseMembers.IsEmpty)) { Split(); applyMemberPostConditions(receiverSlot, type, notNullWhenTrueMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullWhenFalseMembers, ref StateWhenFalse); } method = method.OverriddenMethod; } while (method != null); void applyMemberPostConditions(int receiverSlot, TypeSymbol type, ImmutableArray<string> members, ref LocalState state) { if (members.IsEmpty) { return; } foreach (var memberName in members) { markMembersAsNotNull(receiverSlot, type, memberName, ref state); } } void markMembersAsNotNull(int receiverSlot, TypeSymbol type, string memberName, ref LocalState state) { foreach (Symbol member in type.GetMembers(memberName)) { if (member.IsStatic) { receiverSlot = 0; } switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (GetOrCreateSlot(member, receiverSlot) is int memberSlot && memberSlot > 0) { state[memberSlot] = NullableFlowState.NotNull; } break; case SymbolKind.Event: case SymbolKind.Method: break; } } } } private ImmutableArray<VisitArgumentResult> VisitArgumentsEvaluate( ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<FlowAnalysisAnnotations> parameterAnnotationsOpt, BitVector defaultArguments) { Debug.Assert(!IsConditionalState); int n = arguments.Length; if (n == 0 && parameterAnnotationsOpt.IsDefaultOrEmpty) { return ImmutableArray<VisitArgumentResult>.Empty; } var resultsBuilder = ArrayBuilder<VisitArgumentResult>.GetInstance(n); var previousDisableDiagnostics = _disableDiagnostics; for (int i = 0; i < n; i++) { // we disable nullable warnings on default arguments _disableDiagnostics = defaultArguments[i] || previousDisableDiagnostics; resultsBuilder.Add(VisitArgumentEvaluate(arguments[i], GetRefKind(refKindsOpt, i), parameterAnnotationsOpt.IsDefault ? default : parameterAnnotationsOpt[i])); } _disableDiagnostics = previousDisableDiagnostics; SetInvalidResult(); return resultsBuilder.ToImmutableAndFree(); } private ImmutableArray<FlowAnalysisAnnotations> GetParametersAnnotations(ImmutableArray<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { ImmutableArray<FlowAnalysisAnnotations> parameterAnnotationsOpt = default; if (!parametersOpt.IsDefault) { parameterAnnotationsOpt = arguments.SelectAsArray( (argument, i, arg) => GetCorrespondingParameter(i, arg.parametersOpt, arg.argsToParamsOpt, arg.expanded).Annotations, (parametersOpt, argsToParamsOpt, expanded)); } return parameterAnnotationsOpt; } private VisitArgumentResult VisitArgumentEvaluate(BoundExpression argument, RefKind refKind, FlowAnalysisAnnotations annotations) { Debug.Assert(!IsConditionalState); var savedState = (argument.Kind == BoundKind.Lambda) ? this.State.Clone() : default(Optional<LocalState>); // Note: DoesNotReturnIf is ineffective on ref/out parameters switch (refKind) { case RefKind.Ref: Visit(argument); Unsplit(); break; case RefKind.None: case RefKind.In: switch (annotations & (FlowAnalysisAnnotations.DoesNotReturnIfTrue | FlowAnalysisAnnotations.DoesNotReturnIfFalse)) { case FlowAnalysisAnnotations.DoesNotReturnIfTrue: Visit(argument); if (IsConditionalState) { SetState(StateWhenFalse); } break; case FlowAnalysisAnnotations.DoesNotReturnIfFalse: Visit(argument); if (IsConditionalState) { SetState(StateWhenTrue); } break; default: VisitRvalue(argument); break; } break; case RefKind.Out: // As far as we can tell, there is no scenario relevant to nullability analysis // where splitting an L-value (for instance with a ref conditional) would affect the result. Visit(argument); // We'll want to use the l-value type, rather than the result type, for method re-inference UseLvalueOnly(argument); break; } Debug.Assert(!IsConditionalState); return new VisitArgumentResult(_visitResult, savedState); } /// <summary> /// Verifies that an argument's nullability is compatible with its parameter's on the way in. /// </summary> private void VisitArgumentConversionAndInboundAssignmentsAndPreConditions( BoundConversion? conversionOpt, BoundExpression argumentNoConversion, Conversion conversion, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, ArrayBuilder<VisitResult>? conversionResultsBuilder, bool extensionMethodThisArgument) { Debug.Assert(!this.IsConditionalState); // Note: we allow for some variance in `in` and `out` cases. Unlike in binding, we're not // limited by CLR constraints. var resultType = result.RValueType; switch (refKind) { case RefKind.None: case RefKind.In: { // Note: for lambda arguments, they will be converted in the context/state we saved for that argument if (conversion is { Kind: ConversionKind.ImplicitUserDefined }) { var argumentResultType = resultType.Type; conversion = GenerateConversion(_conversions, argumentNoConversion, argumentResultType, parameterType.Type, fromExplicitCast: false, extensionMethodThisArgument: false, isChecked: conversionOpt?.Checked ?? false); if (!conversion.Exists && !argumentNoConversion.IsSuppressed) { Debug.Assert(argumentResultType is not null); ReportNullabilityMismatchInArgument(argumentNoConversion.Syntax, argumentResultType, parameter, parameterType.Type, forOutput: false); } } var stateAfterConversion = VisitConversion( conversionOpt: conversionOpt, conversionOperand: argumentNoConversion, conversion: conversion, targetTypeWithNullability: ApplyLValueAnnotations(parameterType, parameterAnnotations), operandType: resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter, extensionMethodThisArgument: extensionMethodThisArgument, stateForLambda: result.StateForLambda, previousArgumentConversionResults: conversionResultsBuilder); // If the parameter has annotations, we perform an additional check for nullable value types if (CheckDisallowedNullAssignment(stateAfterConversion, parameterAnnotations, argumentNoConversion.Syntax.Location)) { LearnFromNonNullTest(argumentNoConversion, ref State); } SetResultType(argumentNoConversion, stateAfterConversion, updateAnalyzedNullability: false); conversionResultsBuilder?.Add(_visitResult); } break; case RefKind.Ref: if (!argumentNoConversion.IsSuppressed) { var lvalueResultType = result.LValueType; if (IsNullabilityMismatch(lvalueResultType.Type, parameterType.Type)) { // declared types must match, ignoring top-level nullability ReportNullabilityMismatchInRefArgument(argumentNoConversion, argumentType: lvalueResultType.Type, parameter, parameterType.Type); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(argumentNoConversion, ApplyLValueAnnotations(parameterType, parameterAnnotations), resultType, useLegacyWarnings: false); // If the parameter has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, argumentNoConversion.Syntax.Location); } } conversionResultsBuilder?.Add(result.VisitResult); break; case RefKind.Out: conversionResultsBuilder?.Add(result.VisitResult); break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } Debug.Assert(!this.IsConditionalState); } /// <summary>Returns <see langword="true"/> if this is an assignment forbidden by DisallowNullAttribute, otherwise <see langword="false"/>.</summary> private bool CheckDisallowedNullAssignment(TypeWithState state, FlowAnalysisAnnotations annotations, Location location, BoundExpression? boundValueOpt = null) { if (boundValueOpt is { WasCompilerGenerated: true }) { // We need to skip `return backingField;` in auto-prop getters return false; } // We do this extra check for types whose non-nullable version cannot be represented if (IsDisallowedNullAssignment(state, annotations)) { ReportDiagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, location); return true; } return false; } private static bool IsDisallowedNullAssignment(TypeWithState valueState, FlowAnalysisAnnotations targetAnnotations) { return ((targetAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) && hasNoNonNullableCounterpart(valueState.Type) && valueState.MayBeNull; static bool hasNoNonNullableCounterpart(TypeSymbol? type) { if (type is null) { return false; } // Some types that could receive a maybe-null value have a NotNull counterpart: // [NotNull]string? -> string // [NotNull]string -> string // [NotNull]TClass -> TClass // [NotNull]TClass? -> TClass // // While others don't: // [NotNull]int? -> X // [NotNull]TNullable -> X // [NotNull]TStruct? -> X // [NotNull]TOpen -> X return (type.Kind == SymbolKind.TypeParameter && !type.IsReferenceType) || type.IsNullableTypeOrTypeParameter(); } } /// <summary> /// Verifies that outbound assignments (from parameter to argument) are safe and /// tracks those assignments (or learns from post-condition attributes) /// </summary> private void VisitArgumentOutboundAssignmentsAndPostConditions( BoundExpression argument, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, CompareExchangeInfo compareExchangeInfoOpt) { // Note: the state may be conditional if a previous argument involved a conditional post-condition // The WhenTrue/False states correspond to the invocation returning true/false switch (refKind) { case RefKind.None: case RefKind.In: { // learn from post-conditions [Maybe/NotNull, Maybe/NotNullWhen] without using an assignment LearnFromPostConditions(argument, parameterAnnotations); } break; case RefKind.Ref: { // assign from a fictional value from the parameter to the argument. parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); if (!compareExchangeInfoOpt.IsDefault) { var adjustedState = LearnFromCompareExchangeMethod(in compareExchangeInfoOpt); parameterWithState = TypeWithState.Create(parameterType.Type, adjustedState); } var parameterValue = new BoundParameter(argument.Syntax, parameter); var lValueType = result.LValueType; trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // check whether parameter would unsafely let a null out in the worse case if (!argument.IsSuppressed) { var leftAnnotations = GetLValueAnnotations(argument); ReportNullableAssignmentIfNecessary( parameterValue, targetType: ApplyLValueAnnotations(lValueType, leftAnnotations), valueType: applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations), UseLegacyWarnings(argument, result.LValueType)); } } break; case RefKind.Out: { // compute the fictional parameter state parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); // Adjust parameter state if MaybeNull or MaybeNullWhen are present (for `var` type and for assignment warnings) var worstCaseParameterWithState = applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations); var declaredType = result.LValueType; var leftAnnotations = GetLValueAnnotations(argument); var lValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (argument is BoundLocal local && local.DeclarationKind == BoundLocalDeclarationKind.WithInferredType) { var varType = worstCaseParameterWithState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local.LocalSymbol, varType); lValueType = varType; } else if (argument is BoundDiscardExpression discard) { SetAnalyzedNullability(discard, new VisitResult(parameterWithState, parameterWithState.ToTypeWithAnnotations(compilation)), isLvalue: true); } // track state by assigning from a fictional value from the parameter to the argument. var parameterValue = new BoundParameter(argument.Syntax, parameter); // If the argument type has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(parameterWithState, leftAnnotations, argument.Syntax.Location); AdjustSetValue(argument, ref parameterWithState); trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // report warnings if parameter would unsafely let a null out in the worst case if (!argument.IsSuppressed) { ReportNullableAssignmentIfNecessary(parameterValue, lValueType, worstCaseParameterWithState, UseLegacyWarnings(argument, result.LValueType)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (!_conversions.HasIdentityOrImplicitReferenceConversion(parameterType.Type, lValueType.Type, ref discardedUseSiteInfo)) { ReportNullabilityMismatchInArgument(argument.Syntax, lValueType.Type, parameter, parameterType.Type, forOutput: true); } } } break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } FlowAnalysisAnnotations notNullBasedOnParameters(FlowAnalysisAnnotations parameterAnnotations, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, ParameterSymbol parameter) { if (!IsAnalyzingAttribute && notNullParametersOpt is object) { var notNullIfParameterNotNull = parameter.NotNullIfParameterNotNull; if (!notNullIfParameterNotNull.IsEmpty) { foreach (var notNullParameter in notNullParametersOpt) { if (notNullIfParameterNotNull.Contains(notNullParameter.Name)) { return FlowAnalysisAnnotations.NotNull; } } } } return parameterAnnotations; } void trackNullableStateForAssignment(BoundExpression parameterValue, TypeWithAnnotations lValueType, int targetSlot, TypeWithState parameterWithState, bool isSuppressed, FlowAnalysisAnnotations parameterAnnotations) { if (!IsConditionalState && !hasConditionalPostCondition(parameterAnnotations)) { TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, parameterWithState.WithSuppression(isSuppressed)); } else { Split(); var originalWhenFalse = StateWhenFalse.Clone(); SetState(StateWhenTrue); // Note: the suppression applies over the post-condition attributes TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenTrue(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); var newWhenTrue = State.Clone(); SetState(originalWhenFalse); TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenFalse(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); SetConditionalState(newWhenTrue, whenFalse: State); } } static bool hasConditionalPostCondition(FlowAnalysisAnnotations annotations) { return (((annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0)) || (((annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0)); } static TypeWithState applyPostConditionsUnconditionally(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNull return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenTrue(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && !(maybeNullWhenFalse && notNullWhenTrue)) { // [MaybeNull, NotNullWhen(true)] means [MaybeNullWhen(false)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenTrue) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenFalse(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenFalse && !(maybeNullWhenTrue && notNullWhenFalse)) { // [MaybeNull, NotNullWhen(false)] means [MaybeNullWhen(true)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenFalse) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } } /// <summary> /// Learn from postconditions on a by-value or 'in' argument. /// </summary> private void LearnFromPostConditions(BoundExpression argument, FlowAnalysisAnnotations parameterAnnotations) { // Note: NotNull = NotNullWhen(true) + NotNullWhen(false) bool notNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool notNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; // Note: MaybeNull = MaybeNullWhen(true) + MaybeNullWhen(false) bool maybeNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && maybeNullWhenFalse && !IsConditionalState && !(notNullWhenTrue && notNullWhenFalse)) { LearnFromNullTest(argument, ref State); } else if (notNullWhenTrue && notNullWhenFalse && !IsConditionalState && !(maybeNullWhenTrue || maybeNullWhenFalse)) { LearnFromNonNullTest(argument, ref State); } else if (notNullWhenTrue || notNullWhenFalse || maybeNullWhenTrue || maybeNullWhenFalse) { Split(); if (notNullWhenTrue) { LearnFromNonNullTest(argument, ref StateWhenTrue); } if (notNullWhenFalse) { LearnFromNonNullTest(argument, ref StateWhenFalse); } if (maybeNullWhenTrue) { LearnFromNullTest(argument, ref StateWhenTrue); } if (maybeNullWhenFalse) { LearnFromNullTest(argument, ref StateWhenFalse); } } } private (ImmutableArray<BoundExpression> arguments, ImmutableArray<Conversion> conversions) RemoveArgumentConversions( ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt) { int n = arguments.Length; var conversions = default(ImmutableArray<Conversion>); if (n > 0) { var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); var conversionsBuilder = ArrayBuilder<Conversion>.GetInstance(n); bool includedConversion = false; for (int i = 0; i < n; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); var argument = arguments[i]; var conversion = Conversion.Identity; if (refKind == RefKind.None) { var before = argument; (argument, conversion) = RemoveConversion(argument, includeExplicitConversions: false); if (argument != before) { SnapshotWalkerThroughConversionGroup(before, argument); includedConversion = true; } } argumentsBuilder.Add(argument); conversionsBuilder.Add(conversion); } if (includedConversion) { arguments = argumentsBuilder.ToImmutable(); conversions = conversionsBuilder.ToImmutable(); } argumentsBuilder.Free(); conversionsBuilder.Free(); } return (arguments, conversions); } private static VariableState GetVariableState(Variables variables, LocalState localState) { Debug.Assert(variables.Id == localState.Id); return new VariableState(variables.CreateSnapshot(), localState.CreateSnapshot()); } private (ParameterSymbol? Parameter, TypeWithAnnotations Type, FlowAnalysisAnnotations Annotations, bool isExpandedParamsArgument) GetCorrespondingParameter( int argumentOrdinal, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { if (parametersOpt.IsDefault) { return default; } var parameter = Binder.GetCorrespondingParameter(argumentOrdinal, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { Debug.Assert(!expanded); return default; } var type = parameter.TypeWithAnnotations; if (expanded && parameter.Ordinal == parametersOpt.Length - 1 && type.IsSZArray()) { type = ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations; return (parameter, type, FlowAnalysisAnnotations.None, isExpandedParamsArgument: true); } return (parameter, type, GetParameterAnnotations(parameter), isExpandedParamsArgument: false); } private MethodSymbol InferMethodTypeArguments( MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { Debug.Assert(method.IsGenericMethod); // https://github.com/dotnet/roslyn/issues/27961 OverloadResolution.IsMemberApplicableInNormalForm and // IsMemberApplicableInExpandedForm use the least overridden method. We need to do the same here. var definition = method.ConstructedFrom; var refKinds = ArrayBuilder<RefKind>.GetInstance(); if (argumentRefKindsOpt != null) { refKinds.AddRange(argumentRefKindsOpt); } // https://github.com/dotnet/roslyn/issues/27961 Do we really need OverloadResolution.GetEffectiveParameterTypes? // Aren't we doing roughly the same calculations in GetCorrespondingParameter? OverloadResolution.GetEffectiveParameterTypes( definition, arguments.Length, argsToParamsOpt, refKinds, isMethodGroupConversion: false, // https://github.com/dotnet/roslyn/issues/27961 `allowRefOmittedArguments` should be // false for constructors and several other cases (see Binder use). Should we // capture the original value in the BoundCall? allowRefOmittedArguments: true, binder: _binder, expanded: expanded, parameterTypes: out ImmutableArray<TypeWithAnnotations> parameterTypes, parameterRefKinds: out ImmutableArray<RefKind> parameterRefKinds); refKinds.Free(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var result = MethodTypeInferrer.Infer( _binder, _conversions, definition.TypeParameters, definition.ContainingType, parameterTypes, parameterRefKinds, arguments, ref discardedUseSiteInfo, new MethodInferenceExtensions(this)); if (!result.Success) { return method; } return definition.Construct(result.InferredTypeArguments); } private sealed class MethodInferenceExtensions : MethodTypeInferrer.Extensions { private readonly NullableWalker _walker; internal MethodInferenceExtensions(NullableWalker walker) { _walker = walker; } internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType(), GetNullableAnnotation(expr)); } /// <summary> /// Return top-level nullability for the expression. This method should be called on a limited /// set of expressions only. It should not be called on expressions tracked by flow analysis /// other than <see cref="BoundKind.ExpressionWithNullability"/> which is an expression /// specifically created in NullableWalker to represent the flow analysis state. /// </summary> private static NullableAnnotation GetNullableAnnotation(BoundExpression expr) { switch (expr.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.Literal: return expr.ConstantValue == ConstantValue.NotAvailable || !expr.ConstantValue.IsNull || expr.IsSuppressed ? NullableAnnotation.NotAnnotated : NullableAnnotation.Annotated; case BoundKind.ExpressionWithNullability: return ((BoundExpressionWithNullability)expr).NullableAnnotation; case BoundKind.MethodGroup: case BoundKind.UnboundLambda: case BoundKind.UnconvertedObjectCreationExpression: case BoundKind.ConvertedTupleLiteral: return NullableAnnotation.NotAnnotated; default: Debug.Assert(false); // unexpected value return NullableAnnotation.Oblivious; } } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { if (_walker.TryGetMethodGroupReceiverNullability(group.ReceiverOpt, out TypeWithState receiverType)) { if (!method.IsStatic) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } } return method.ReturnTypeWithAnnotations; } } private ImmutableArray<BoundExpression> GetArgumentsForMethodTypeInference(ImmutableArray<VisitArgumentResult> argumentResults, ImmutableArray<BoundExpression> arguments) { // https://github.com/dotnet/roslyn/issues/27961 MethodTypeInferrer.Infer relies // on the BoundExpressions for tuple element types and method groups. // By using a generic BoundValuePlaceholder, we're losing inference in those cases. // https://github.com/dotnet/roslyn/issues/27961 Inference should be based on // unconverted arguments. Consider cases such as `default`, lambdas, tuples. int n = argumentResults.Length; var builder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var visitArgumentResult = argumentResults[i]; var lambdaState = visitArgumentResult.StateForLambda; // Note: for `out` arguments, the argument result contains the declaration type (see `VisitArgumentEvaluate`) var argumentResult = visitArgumentResult.RValueType.ToTypeWithAnnotations(compilation); builder.Add(getArgumentForMethodTypeInference(arguments[i], argumentResult, lambdaState)); } return builder.ToImmutableAndFree(); BoundExpression getArgumentForMethodTypeInference(BoundExpression argument, TypeWithAnnotations argumentType, Optional<LocalState> lambdaState) { if (argument.Kind == BoundKind.Lambda) { Debug.Assert(lambdaState.HasValue); // MethodTypeInferrer must infer nullability for lambdas based on the nullability // from flow analysis rather than the declared nullability. To allow that, we need // to re-bind lambdas in MethodTypeInferrer. return getUnboundLambda((BoundLambda)argument, GetVariableState(_variables, lambdaState.Value)); } if (!argumentType.HasType) { return argument; } if (argument is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } || IsTargetTypedExpression(argument)) { // target-typed contexts don't contribute to nullability return new BoundExpressionWithNullability(argument.Syntax, argument, NullableAnnotation.Oblivious, type: null); } return new BoundExpressionWithNullability(argument.Syntax, argument, argumentType.NullableAnnotation, argumentType.Type); } static UnboundLambda getUnboundLambda(BoundLambda expr, VariableState variableState) { return expr.UnboundLambda.WithNullableState(variableState); } } private void CheckMethodConstraints(SyntaxNode syntax, MethodSymbol method) { if (_disableDiagnostics) { return; } var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); var nullabilityBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); ArrayBuilder<TypeParameterDiagnosticInfo>? useSiteDiagnosticsBuilder = null; ConstraintsHelper.CheckMethodConstraints( method, new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, NoLocation.Singleton, diagnostics: null, template: CompoundUseSiteInfo<AssemblySymbol>.Discarded), diagnosticsBuilder, nullabilityBuilder, ref useSiteDiagnosticsBuilder); foreach (var pair in nullabilityBuilder) { if (pair.UseSiteInfo.DiagnosticInfo is object) { Diagnostics.Add(pair.UseSiteInfo.DiagnosticInfo, syntax.Location); } } useSiteDiagnosticsBuilder?.Free(); nullabilityBuilder.Free(); diagnosticsBuilder.Free(); } /// <summary> /// Returns the expression without the top-most conversion plus the conversion. /// If the expression is not a conversion, returns the original expression plus /// the Identity conversion. If `includeExplicitConversions` is true, implicit and /// explicit conversions are considered. If `includeExplicitConversions` is false /// only implicit conversions are considered and if the expression is an explicit /// conversion, the expression is returned as is, with the Identity conversion. /// (Currently, the only visit method that passes `includeExplicitConversions: true` /// is VisitConversion. All other callers are handling implicit conversions only.) /// </summary> private static (BoundExpression expression, Conversion conversion) RemoveConversion(BoundExpression expr, bool includeExplicitConversions) { ConversionGroup? group = null; while (true) { if (expr.Kind != BoundKind.Conversion) { break; } var conversion = (BoundConversion)expr; if (group != conversion.ConversionGroupOpt && group != null) { // E.g.: (C)(B)a break; } group = conversion.ConversionGroupOpt; Debug.Assert(group != null || !conversion.ExplicitCastInCode); // Explicit conversions should include a group. if (!includeExplicitConversions && group?.IsExplicitConversion == true) { return (expr, Conversion.Identity); } expr = conversion.Operand; if (group == null) { // Ungrouped conversion should not be followed by another ungrouped // conversion. Otherwise, the conversions should have been grouped. // https://github.com/dotnet/roslyn/issues/34919 This assertion does not always hold true for // enum initializers //Debug.Assert(expr.Kind != BoundKind.Conversion || // ((BoundConversion)expr).ConversionGroupOpt != null || // ((BoundConversion)expr).ConversionKind == ConversionKind.NoConversion); return (expr, conversion.Conversion); } } return (expr, group?.Conversion ?? Conversion.Identity); } // See Binder.BindNullCoalescingOperator for initial binding. private Conversion GenerateConversionForConditionalOperator(BoundExpression sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool reportMismatch, bool isChecked) { var conversion = GenerateConversion(_conversions, sourceExpression, sourceType, destinationType, fromExplicitCast: false, extensionMethodThisArgument: false, isChecked: isChecked); bool canConvertNestedNullability = conversion.Exists; if (!canConvertNestedNullability && reportMismatch && !sourceExpression.IsSuppressed) { ReportNullabilityMismatchInAssignment(sourceExpression.Syntax, GetTypeAsDiagnosticArgument(sourceType), destinationType); } return conversion; } private static Conversion GenerateConversion(Conversions conversions, BoundExpression? sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool fromExplicitCast, bool extensionMethodThisArgument, bool isChecked) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool useExpression = sourceType is null || UseExpressionForConversion(sourceExpression); if (extensionMethodThisArgument) { return conversions.ClassifyImplicitExtensionMethodThisArgConversion( useExpression ? sourceExpression : null, sourceType, destinationType, ref discardedUseSiteInfo); } return useExpression ? (fromExplicitCast ? conversions.ClassifyConversionFromExpression(sourceExpression, destinationType, isChecked: isChecked, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromExpression(sourceExpression!, destinationType, ref discardedUseSiteInfo)) : (fromExplicitCast ? conversions.ClassifyConversionFromType(sourceType, destinationType, isChecked: isChecked, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromType(sourceType!, destinationType, ref discardedUseSiteInfo)); } /// <summary> /// Returns true if the expression should be used as the source when calculating /// a conversion from this expression, rather than using the type (with nullability) /// calculated by visiting this expression. Typically, that means expressions that /// do not have an explicit type but there are several other cases as well. /// (See expressions handled in ClassifyImplicitBuiltInConversionFromExpression.) /// </summary> private static bool UseExpressionForConversion([NotNullWhen(true)] BoundExpression? value) { if (value is null) { return false; } if (value.Type is null || value.Type.IsDynamic() || value.ConstantValue != null) { return true; } switch (value.Kind) { case BoundKind.InterpolatedString: return true; default: return false; } } /// <summary> /// Adjust declared type based on inferred nullability at the point of reference. /// </summary> private TypeWithState GetAdjustedResult(TypeWithState type, int slot) { if (this.State.HasValue(slot)) { NullableFlowState state = this.State[slot]; return TypeWithState.Create(type.Type, state); } return type; } /// <summary> /// Gets the corresponding member for a symbol from initial binding to match an updated receiver type in NullableWalker. /// For instance, this will map from List&lt;string~&gt;.Add(string~) to List&lt;string?&gt;.Add(string?) in the following example: /// <example> /// string s = null; /// var list = new[] { s }.ToList(); /// list.Add(null); /// </example> /// </summary> private static Symbol AsMemberOfType(TypeSymbol? type, Symbol symbol) { Debug.Assert((object)symbol != null); var containingType = type as NamedTypeSymbol; if (containingType is null || containingType.IsErrorType() || symbol is ErrorMethodSymbol) { return symbol; } if (symbol.Kind == SymbolKind.Method) { if (((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction) { // https://github.com/dotnet/roslyn/issues/27233 Handle type substitution for local functions. return symbol; } } if (symbol is TupleElementFieldSymbol or TupleErrorFieldSymbol) { return symbol.SymbolAsMember(containingType); } var symbolContainer = symbol.ContainingType; if (symbolContainer.IsAnonymousType) { int? memberIndex = symbol.Kind == SymbolKind.Property ? symbol.MemberIndexOpt : null; if (!memberIndex.HasValue) { return symbol; } return AnonymousTypeManager.GetAnonymousTypeProperty(containingType, memberIndex.GetValueOrDefault()); } if (!symbolContainer.IsGenericType) { Debug.Assert(symbol.ContainingType.IsDefinition); return symbol; } if (!containingType.IsGenericType) { return symbol; } if (symbolContainer.IsInterface) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } foreach (var @interface in containingType.AllInterfacesNoUseSiteDiagnostics) { if (tryAsMemberOfSingleType(@interface, out result)) { return result; } } } else { while (true) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } containingType = containingType.BaseTypeNoUseSiteDiagnostics; if ((object)containingType == null) { break; } } } Debug.Assert(false); // If this assert fails, add an appropriate test. return symbol; bool tryAsMemberOfSingleType(NamedTypeSymbol singleType, [NotNullWhen(true)] out Symbol? result) { if (!singleType.Equals(symbolContainer, TypeCompareKind.AllIgnoreOptions)) { result = null; return false; } var symbolDef = symbol.OriginalDefinition; result = symbolDef.SymbolAsMember(singleType); if (result is MethodSymbol resultMethod && resultMethod.IsGenericMethod) { result = resultMethod.Construct(((MethodSymbol)symbol).TypeArgumentsWithAnnotations); } return true; } } public override BoundNode? VisitConversion(BoundConversion node) { // https://github.com/dotnet/roslyn/issues/35732: Assert VisitConversion is only used for explicit conversions. //Debug.Assert(node.ExplicitCastInCode); //Debug.Assert(node.ConversionGroupOpt != null); //Debug.Assert(node.ConversionGroupOpt.ExplicitType.HasType); TypeWithAnnotations explicitType = node.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(node.Type); Debug.Assert(targetType.HasType); (BoundExpression operand, Conversion conversion) = RemoveConversion(node, includeExplicitConversions: true); SnapshotWalkerThroughConversionGroup(node, operand); TypeWithState operandType = VisitRvalueWithState(operand); SetResultType(node, VisitConversion( node, operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: fromExplicitCast, useLegacyWarnings: fromExplicitCast, AssignmentKind.Assignment, reportTopLevelWarnings: fromExplicitCast, reportRemainingWarnings: true, trackMembers: true)); return null; } /// <summary> /// Visit an expression. If an explicit target type is provided, the expression is converted /// to that type. This method should be called whenever an expression may contain /// an implicit conversion, even if that conversion was omitted from the bound tree, /// so the conversion can be re-classified with nullability. /// </summary> private TypeWithState VisitOptionalImplicitConversion(BoundExpression expr, TypeWithAnnotations targetTypeOpt, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind) { if (!targetTypeOpt.HasType) { return VisitRvalueWithState(expr); } var (resultType, completion) = VisitOptionalImplicitConversion(expr, targetTypeOpt, useLegacyWarnings, trackMembers, assignmentKind, delayCompletionForTargetType: false); Debug.Assert(completion is null); return resultType; } private (TypeWithState resultType, Func<TypeWithAnnotations, TypeWithState>? completion) VisitOptionalImplicitConversion( BoundExpression expr, TypeWithAnnotations targetTypeOpt, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind, bool delayCompletionForTargetType) { (BoundExpression operand, Conversion conversion) = RemoveConversion(expr, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(expr, operand); var operandType = VisitRvalueWithState(operand); return visitConversion(expr, targetTypeOpt, useLegacyWarnings, trackMembers, assignmentKind, operand, conversion, operandType, delayCompletionForTargetType); (TypeWithState resultType, Func<TypeWithAnnotations, TypeWithState>? completion) visitConversion( BoundExpression expr, TypeWithAnnotations targetTypeOpt, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind, BoundExpression operand, Conversion conversion, TypeWithState operandType, bool delayCompletionForTargetType) { if (delayCompletionForTargetType) { return (TypeWithState.Create(targetTypeOpt), visitConversionAsContinuation(expr, useLegacyWarnings, trackMembers, assignmentKind, operand, conversion, operandType)); } Debug.Assert(targetTypeOpt.HasType); // If an explicit conversion was used in place of an implicit conversion, the explicit // conversion was created by initial binding after reporting "error CS0266: // Cannot implicitly convert type '...' to '...'. An explicit conversion exists ...". // Since an error was reported, we don't need to report nested warnings as well. bool reportNestedWarnings = !conversion.IsExplicit; var resultType = VisitConversion( GetConversionIfApplicable(expr, operand), operand, conversion, targetTypeOpt, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: useLegacyWarnings, assignmentKind, reportTopLevelWarnings: true, reportRemainingWarnings: reportNestedWarnings, trackMembers: trackMembers); return (resultType, null); } Func<TypeWithAnnotations, TypeWithState> visitConversionAsContinuation(BoundExpression expr, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind, BoundExpression operand, Conversion conversion, TypeWithState operandType) { return (TypeWithAnnotations targetTypeOpt) => { var result = visitConversion(expr, targetTypeOpt, useLegacyWarnings, trackMembers, assignmentKind, operand, conversion, operandType, delayCompletionForTargetType: false); Debug.Assert(result.completion is null); return result.resultType; }; } } private static bool AreNullableAndUnderlyingTypes([NotNullWhen(true)] TypeSymbol? nullableTypeOpt, [NotNullWhen(true)] TypeSymbol? underlyingTypeOpt, out TypeWithAnnotations underlyingTypeWithAnnotations) { if (nullableTypeOpt?.IsNullableType() == true && underlyingTypeOpt?.IsNullableType() == false) { var typeArg = nullableTypeOpt.GetNullableUnderlyingTypeWithAnnotations(); if (typeArg.Type.Equals(underlyingTypeOpt, TypeCompareKind.AllIgnoreOptions)) { underlyingTypeWithAnnotations = typeArg; return true; } } underlyingTypeWithAnnotations = default; return false; } public override BoundNode? VisitTupleLiteral(BoundTupleLiteral node) { VisitTupleExpression(node); return null; } public override BoundNode? VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { Debug.Assert(!IsConditionalState); var savedState = this.State.Clone(); // Visit the source tuple so that the semantic model can correctly report nullability for it // Disable diagnostics, as we don't want to duplicate any that are produced by visiting the converted literal below VisitWithoutDiagnostics(node.SourceTuple); this.SetState(savedState); VisitTupleExpression(node); return null; } private void VisitTupleExpression(BoundTupleExpression node) { var arguments = node.Arguments; ImmutableArray<TypeWithState> elementTypes = arguments.SelectAsArray((a, w) => w.VisitRvalueWithState(a), this); ImmutableArray<TypeWithAnnotations> elementTypesWithAnnotations = elementTypes.SelectAsArray(a => a.ToTypeWithAnnotations(compilation)); var tupleOpt = (NamedTypeSymbol?)node.Type; if (tupleOpt is null) { SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); } else { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; TrackNullableStateOfTupleElements(slot, tupleOpt, arguments, elementTypes, argsToParamsOpt: default, useRestField: false); } tupleOpt = tupleOpt.WithElementTypes(elementTypesWithAnnotations); if (!_disableDiagnostics) { var locations = tupleOpt.TupleElements.SelectAsArray((element, location) => element.Locations.FirstOrDefault() ?? location, node.Syntax.Location); tupleOpt.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, node.Syntax.Location, diagnostics: null), typeSyntax: node.Syntax, locations, nullabilityDiagnosticsOpt: new BindingDiagnosticBag(Diagnostics)); } SetResultType(node, TypeWithState.Create(tupleOpt, NullableFlowState.NotNull)); } } /// <summary> /// Set the nullability of tuple elements for tuples at the point of construction. /// If <paramref name="useRestField"/> is true, the tuple was constructed with an explicit /// 'new ValueTuple' call, in which case the 8-th element, if any, represents the 'Rest' field. /// </summary> private void TrackNullableStateOfTupleElements( int slot, NamedTypeSymbol tupleType, ImmutableArray<BoundExpression> values, ImmutableArray<TypeWithState> types, ImmutableArray<int> argsToParamsOpt, bool useRestField) { Debug.Assert(tupleType.IsTupleType); Debug.Assert(values.Length == types.Length); Debug.Assert(values.Length == (useRestField ? Math.Min(tupleType.TupleElements.Length, NamedTypeSymbol.ValueTupleRestPosition) : tupleType.TupleElements.Length)); if (slot > 0) { var tupleElements = tupleType.TupleElements; int n = values.Length; if (useRestField) { n = Math.Min(n, NamedTypeSymbol.ValueTupleRestPosition - 1); } for (int i = 0; i < n; i++) { var argOrdinal = getArgumentOrdinalFromParameterOrdinal(i); trackState(values[argOrdinal], tupleElements[i], types[argOrdinal]); } if (useRestField && values.Length == NamedTypeSymbol.ValueTupleRestPosition && tupleType.GetMembers(NamedTypeSymbol.ValueTupleRestFieldName).FirstOrDefault() is FieldSymbol restField) { var argOrdinal = getArgumentOrdinalFromParameterOrdinal(NamedTypeSymbol.ValueTupleRestPosition - 1); trackState(values[argOrdinal], restField, types[argOrdinal]); } } void trackState(BoundExpression value, FieldSymbol field, TypeWithState valueType) { int targetSlot = GetOrCreateSlot(field, slot); TrackNullableStateForAssignment(value, field.TypeWithAnnotations, targetSlot, valueType, MakeSlot(value)); } int getArgumentOrdinalFromParameterOrdinal(int parameterOrdinal) { var index = argsToParamsOpt.IsDefault ? parameterOrdinal : argsToParamsOpt.IndexOf(parameterOrdinal); Debug.Assert(index != -1); return index; } } private void TrackNullableStateOfNullableValue(int containingSlot, TypeSymbol containingType, BoundExpression? value, TypeWithState valueType, int valueSlot) { Debug.Assert(containingType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T); Debug.Assert(containingSlot > 0); Debug.Assert(valueSlot > 0); int targetSlot = GetNullableOfTValueSlot(containingType, containingSlot, out Symbol? symbol); if (targetSlot > 0) { TrackNullableStateForAssignment(value, symbol!.GetTypeOrReturnType(), targetSlot, valueType, valueSlot); } } private void TrackNullableStateOfTupleConversion( BoundConversion? conversionOpt, BoundExpression convertedNode, Conversion conversion, TypeSymbol targetType, TypeSymbol operandType, int slot, int valueSlot, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings) { Debug.Assert(conversion.Kind == ConversionKind.ImplicitTuple || conversion.Kind == ConversionKind.ExplicitTuple); Debug.Assert(slot > 0); Debug.Assert(valueSlot > 0); var valueTuple = operandType as NamedTypeSymbol; if (valueTuple is null || !valueTuple.IsTupleType) { return; } var conversions = conversion.UnderlyingConversions; var targetElements = ((NamedTypeSymbol)targetType).TupleElements; var valueElements = valueTuple.TupleElements; int n = valueElements.Length; for (int i = 0; i < n; i++) { trackConvertedValue(targetElements[i], conversions[i], valueElements[i]); } void trackConvertedValue(FieldSymbol targetField, Conversion conversion, FieldSymbol valueField) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: case ConversionKind.Boxing: case ConversionKind.Unboxing: InheritNullableStateOfMember(slot, valueSlot, valueField, isDefaultValue: false, skipSlot: slot); break; case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, convertedNode, conversion, targetField.Type, valueField.Type, targetFieldSlot, valueFieldSlot, assignmentKind, parameterOpt, reportWarnings); } } } break; case ConversionKind.ImplicitNullable: case ConversionKind.ExplicitNullable: // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (AreNullableAndUnderlyingTypes(targetField.Type, valueField.Type, out _)) { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfNullableValue(targetFieldSlot, targetField.Type, null, valueField.TypeWithAnnotations.ToTypeWithState(), valueFieldSlot); } } } break; case ConversionKind.ImplicitUserDefined: case ConversionKind.ExplicitUserDefined: { var convertedType = VisitUserDefinedConversion( conversionOpt, convertedNode, conversion, targetField.TypeWithAnnotations, valueField.TypeWithAnnotations.ToTypeWithState(), useLegacyWarnings: false, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: reportWarnings, diagnosticLocation: (conversionOpt ?? convertedNode).Syntax.GetLocation()); int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = convertedType.State; } } break; default: break; } } } public override BoundNode? VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { base.VisitTupleBinaryOperator(node); SetNotNullResult(node); return null; } private void ReportNullabilityMismatchWithTargetDelegate(Location location, TypeSymbol targetType, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool invokedAsExtensionMethod) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, targetInvokeMethod, sourceInvokeMethod, new BindingDiagnosticBag(Diagnostics), reportBadDelegateReturn, reportBadDelegateParameter, extraArgument: (targetType, location), invokedAsExtensionMethod: invokedAsExtensionMethod); void reportBadDelegateReturn(BindingDiagnosticBag bag, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, arg.location, new FormattedSymbol(sourceInvokeMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), arg.targetType); } void reportBadDelegateParameter(BindingDiagnosticBag bag, MethodSymbol sourceInvokeMethod, MethodSymbol targetInvokeMethod, ParameterSymbol parameter, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, arg.location, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter), arg.targetType); } } private void ReportNullabilityMismatchWithTargetDelegate(Location location, NamedTypeSymbol delegateType, BoundLambda lambda) { MethodSymbol? targetInvokeMethod = delegateType.DelegateInvokeMethod; LambdaSymbol sourceMethod = lambda.Symbol; UnboundLambda unboundLambda = lambda.UnboundLambda; if (targetInvokeMethod is null || targetInvokeMethod.ParameterCount != sourceMethod.ParameterCount) { return; } // Parameter nullability is expected to match exactly. This corresponds to the behavior of initial binding. // Action<string> x = (object o) => { }; // error CS1661: Cannot convert lambda expression to delegate type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<object> y = (object? o) => { }; // warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'Action<object>'. // We check that by calling CheckValidNullableMethodOverride in both directions. // https://github.com/dotnet/roslyn/issues/35564: Consider relaxing and allow implicit conversions of nullability (as we do for method group conversions). if (lambda.Syntax is LambdaExpressionSyntax lambdaSyntax) { int start = lambdaSyntax.SpanStart; location = Location.Create(lambdaSyntax.SyntaxTree, new Text.TextSpan(start, lambdaSyntax.ArrowToken.Span.End - start)); } var diagnostics = new BindingDiagnosticBag(Diagnostics); if (SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, targetInvokeMethod, sourceMethod, diagnostics, reportBadDelegateReturn, reportBadDelegateParameter, extraArgument: location, invokedAsExtensionMethod: false)) { return; } SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, sourceMethod, targetInvokeMethod, diagnostics, reportBadDelegateReturn, reportBadDelegateParameter, extraArgument: location, invokedAsExtensionMethod: false); void reportBadDelegateReturn(BindingDiagnosticBag bag, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool topLevel, Location location) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, location, unboundLambda.MessageID.Localize(), delegateType); } void reportBadDelegateParameter(BindingDiagnosticBag bag, MethodSymbol sourceInvokeMethod, MethodSymbol targetInvokeMethod, ParameterSymbol parameterSymbol, bool topLevel, Location location) { // For anonymous functions with implicit parameters, no need to report this since the parameters can't be referenced if (unboundLambda.HasSignature) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, location, unboundLambda.ParameterName(parameterSymbol.Ordinal), unboundLambda.MessageID.Localize(), delegateType); } } } /// <summary> /// Gets the conversion node for passing to VisitConversion, if one should be passed. /// </summary> private static BoundConversion? GetConversionIfApplicable(BoundExpression? conversionOpt, BoundExpression convertedNode) { Debug.Assert(conversionOpt is null || convertedNode == conversionOpt // Note that convertedNode itself can be a BoundConversion, so we do this check explicitly // because the below calls to RemoveConversion could potentially strip that conversion. || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: false).expression || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: true).expression); return conversionOpt == convertedNode ? null : (BoundConversion?)conversionOpt; } /// <summary> /// Apply the conversion to the type of the operand and return the resulting type. /// If the operand does not have an explicit type, the operand expression is used. /// </summary> /// <param name="checkConversion"> /// If <see langword="true"/>, the incoming conversion is assumed to be from binding /// and will be re-calculated, this time considering nullability. /// Note that the conversion calculation considers nested nullability only. /// The caller is responsible for checking the top-level nullability of /// the type returned by this method. /// </param> /// <param name="trackMembers"> /// If <see langword="true"/>, the nullability of any members of the operand /// will be copied to the converted result when possible. /// </param> /// <param name="useLegacyWarnings"> /// If <see langword="true"/>, indicates that the "non-safety" diagnostic <see cref="ErrorCode.WRN_ConvertingNullableToNonNullable"/> /// should be given for an invalid conversion. /// </param> private TypeWithState VisitConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool checkConversion, bool fromExplicitCast, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt = null, bool reportTopLevelWarnings = true, bool reportRemainingWarnings = true, bool extensionMethodThisArgument = false, Optional<LocalState> stateForLambda = default, bool trackMembers = false, Location? diagnosticLocationOpt = null, ArrayBuilder<VisitResult>? previousArgumentConversionResults = null) { Debug.Assert(!trackMembers || !IsConditionalState); Debug.Assert(conversionOperand != null); if (IsTargetTypedExpression(conversionOperand)) { if (TargetTypedAnalysisCompletion.TryGetValue(conversionOperand, out Func<TypeWithAnnotations, TypeWithState>? completion)) { TargetTypedAnalysisCompletion.Remove(conversionOperand); #if DEBUG bool save_completingTargetTypedExpression = _completingTargetTypedExpression; _completingTargetTypedExpression = true; #endif if (conversionOperand is BoundObjectCreationExpressionBase && targetTypeWithNullability.IsNullableType()) { operandType = completion(targetTypeWithNullability.Type.GetNullableUnderlyingTypeWithAnnotations()); conversion = Conversion.MakeNullableConversion(ConversionKind.ImplicitNullable, Conversion.Identity); } else { operandType = completion(targetTypeWithNullability); } #if DEBUG _completingTargetTypedExpression = save_completingTargetTypedExpression; #endif } else { Debug.Assert(conversionOpt is null); } } NullableFlowState resultState = NullableFlowState.NotNull; bool canConvertNestedNullability = true; bool isSuppressed = false; diagnosticLocationOpt ??= (conversionOpt ?? conversionOperand).Syntax.GetLocation(); if (conversionOperand.IsSuppressed == true) { reportTopLevelWarnings = false; reportRemainingWarnings = false; isSuppressed = true; } #nullable disable TypeSymbol targetType = targetTypeWithNullability.Type; switch (conversion.Kind) { case ConversionKind.MethodGroup: { var group = conversionOperand as BoundMethodGroup; var (invokeSignature, parameters) = getDelegateOrFunctionPointerInfo(targetType); var method = conversion.Method; if (group != null) { if (method?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } method = CheckMethodGroupReceiverNullability(group, parameters, method, conversion.IsExtensionMethod); } if (reportRemainingWarnings && invokeSignature != null) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, targetType, invokeSignature, method, conversion.IsExtensionMethod); } } resultState = NullableFlowState.NotNull; break; static (MethodSymbol invokeSignature, ImmutableArray<ParameterSymbol>) getDelegateOrFunctionPointerInfo(TypeSymbol targetType) => targetType switch { NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { Parameters: { } parameters } signature } => (signature, parameters), FunctionPointerTypeSymbol { Signature: { Parameters: { } parameters } signature } => (signature, parameters), _ => (null, ImmutableArray<ParameterSymbol>.Empty), }; case ConversionKind.AnonymousFunction: if (conversionOperand is BoundLambda lambda) { var delegateType = targetType.GetDelegateType(); VisitLambda(lambda, delegateType, stateForLambda); if (reportRemainingWarnings) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, delegateType, lambda); } TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); return TypeWithState.Create(targetType, NullableFlowState.NotNull); } break; case ConversionKind.FunctionType: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedString: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedStringHandler: visitInterpolatedStringHandlerConstructor(); resultState = NullableFlowState.NotNull; break; case ConversionKind.ObjectCreation: case ConversionKind.SwitchExpression: case ConversionKind.ConditionalExpression: resultState = getConversionResultState(operandType); break; case ConversionKind.ExplicitUserDefined: case ConversionKind.ImplicitUserDefined: return VisitUserDefinedConversion(conversionOpt, conversionOperand, conversion, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt); case ConversionKind.ExplicitDynamic: case ConversionKind.ImplicitDynamic: resultState = getConversionResultState(operandType); break; case ConversionKind.Boxing: resultState = getBoxingConversionResultState(targetTypeWithNullability, operandType); break; case ConversionKind.Unboxing: if (targetType.IsNonNullableValueType()) { if (!operandType.IsNotNull && reportRemainingWarnings) { ReportDiagnostic(ErrorCode.WRN_UnboxPossibleNull, diagnosticLocationOpt); } LearnFromNonNullTest(conversionOperand, ref State); } else { resultState = getUnboxingConversionResultState(operandType); } break; case ConversionKind.ImplicitThrow: resultState = NullableFlowState.NotNull; break; case ConversionKind.NoConversion: resultState = getConversionResultState(operandType); break; case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: checkConversion = false; goto case ConversionKind.Identity; case ConversionKind.Identity: // If the operand is an explicit conversion, and this identity conversion // is converting to the same type including nullability, skip the conversion // to avoid reporting redundant warnings. Also check useLegacyWarnings // since that value was used when reporting warnings for the explicit cast. // Don't skip the node when it's a user-defined conversion, as identity conversions // on top of user-defined conversions means that we're coming in from VisitUserDefinedConversion // and that any warnings caught by this recursive call of VisitConversion won't be redundant. if (useLegacyWarnings && conversionOperand is BoundConversion operandConversion && !operandConversion.ConversionKind.IsUserDefinedConversion()) { var explicitType = operandConversion.ConversionGroupOpt?.ExplicitType; if (explicitType?.Equals(targetTypeWithNullability, TypeCompareKind.ConsiderEverything) == true) { TrackAnalyzedNullabilityThroughConversionGroup( calculateResultType(targetTypeWithNullability, fromExplicitCast, operandType.State, isSuppressed, targetType), conversionOpt, conversionOperand); return operandType; } } if (operandType.Type?.IsTupleType == true || conversionOperand.Kind == BoundKind.TupleLiteral) { goto case ConversionKind.ImplicitTuple; } goto case ConversionKind.ImplicitReference; case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: // Inherit state from the operand. if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument, isChecked: conversionOpt?.Checked ?? false); canConvertNestedNullability = conversion.Exists; } resultState = conversion.IsReference ? getReferenceConversionResultState(targetTypeWithNullability, operandType) : operandType.State; break; case ConversionKind.ImplicitNullable: if (trackMembers) { Debug.Assert(conversionOperand != null); if (AreNullableAndUnderlyingTypes(targetType, operandType.Type, out TypeWithAnnotations underlyingType)) { // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int containingSlot = GetOrCreatePlaceholderSlot(conversionOpt); Debug.Assert(containingSlot > 0); TrackNullableStateOfNullableValue(containingSlot, targetType, conversionOperand, underlyingType.ToTypeWithState(), valueSlot); } } } if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument, isChecked: conversionOpt?.Checked ?? false); canConvertNestedNullability = conversion.Exists; } resultState = operandType.State; break; case ConversionKind.ExplicitNullable: if (operandType.Type?.IsNullableType() == true && !targetType.IsNullableType()) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. if (reportTopLevelWarnings && operandType.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, diagnosticLocationOpt); } // Mark the value as not nullable, regardless of whether it was known to be nullable, // because the implied call to `.Value` will only succeed if not null. if (conversionOperand != null) { LearnFromNonNullTest(conversionOperand, ref State); } } goto case ConversionKind.ImplicitNullable; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ExplicitTuple: if (trackMembers) { Debug.Assert(conversionOperand != null); switch (conversion.Kind) { case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int slot = GetOrCreatePlaceholderSlot(conversionOpt); if (slot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, conversionOperand, conversion, targetType, operandType.Type, slot, valueSlot, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings); } } break; } } if (checkConversion && !targetType.IsErrorType()) { // https://github.com/dotnet/roslyn/issues/29699: Report warnings for user-defined conversions on tuple elements. conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument, isChecked: conversionOpt?.Checked ?? false); canConvertNestedNullability = conversion.Exists; } resultState = NullableFlowState.NotNull; break; case ConversionKind.Deconstruction: // Can reach here, with an error type, when the // Deconstruct method is missing or inaccessible. break; case ConversionKind.ExplicitEnumeration: // Can reach here, with an error type. break; default: Debug.Assert(targetType.IsValueType || targetType.IsErrorType()); break; } TypeWithState resultType = calculateResultType(targetTypeWithNullability, fromExplicitCast, resultState, isSuppressed, targetType); if (!conversionOperand.HasErrors && !targetType.IsErrorType()) { // Need to report all warnings that apply since the warnings can be suppressed individually. if (reportTopLevelWarnings) { ReportNullableAssignmentIfNecessary(conversionOperand, targetTypeWithNullability, resultType, useLegacyWarnings, assignmentKind, parameterOpt, diagnosticLocationOpt); } if (reportRemainingWarnings && !canConvertNestedNullability) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocationOpt, operandType.Type, parameterOpt, targetType, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocationOpt, GetTypeAsDiagnosticArgument(operandType.Type), targetType); } } } TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; #nullable enable static TypeWithState calculateResultType(TypeWithAnnotations targetTypeWithNullability, bool fromExplicitCast, NullableFlowState resultState, bool isSuppressed, TypeSymbol targetType) { if (isSuppressed) { resultState = NullableFlowState.NotNull; } else if (fromExplicitCast && targetTypeWithNullability.NullableAnnotation.IsAnnotated() && !targetType.IsNullableType()) { // An explicit cast to a nullable reference type introduces nullability resultState = targetType?.IsTypeParameterDisallowingAnnotationInCSharp8() == true ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } var resultType = TypeWithState.Create(targetType, resultState); return resultType; } static NullableFlowState getReferenceConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; switch (state) { case NullableFlowState.MaybeNull: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == true) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && dependsOnTypeParameter(typeParameter1, (TypeParameterSymbol)targetType.Type, NullableAnnotation.NotAnnotated, out var annotation)) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } break; case NullableFlowState.MaybeDefault: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == false) { return NullableFlowState.MaybeNull; } break; } return state; } // Converting to a less-derived type (object, interface, type parameter). // If the operand is MaybeNull, the result should be // MaybeNull (if the target type allows) or MaybeDefault otherwise. static NullableFlowState getBoxingConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && targetType.Type is TypeParameterSymbol typeParameter2) { bool dependsOn = dependsOnTypeParameter(typeParameter1, typeParameter2, NullableAnnotation.NotAnnotated, out var annotation); Debug.Assert(dependsOn); // If this case fails, add a corresponding test. if (dependsOn) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } return state; } // Converting to a more-derived type (struct, class, type parameter). // If the operand is MaybeNull or MaybeDefault, the result should be // MaybeDefault. static NullableFlowState getUnboxingConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } static NullableFlowState getConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } // If type parameter 1 depends on type parameter 2 (that is, if type parameter 2 appears // in the constraint types of type parameter 1), returns the effective annotation on // type parameter 2 in the constraints of type parameter 1. static bool dependsOnTypeParameter(TypeParameterSymbol typeParameter1, TypeParameterSymbol typeParameter2, NullableAnnotation typeParameter1Annotation, out NullableAnnotation annotation) { if (typeParameter1.Equals(typeParameter2, TypeCompareKind.AllIgnoreOptions)) { annotation = typeParameter1Annotation; return true; } bool dependsOn = false; var combinedAnnotation = NullableAnnotation.Annotated; foreach (var constraintType in typeParameter1.ConstraintTypesNoUseSiteDiagnostics) { if (constraintType.Type is TypeParameterSymbol constraintTypeParameter && dependsOnTypeParameter(constraintTypeParameter, typeParameter2, constraintType.NullableAnnotation, out var constraintAnnotation)) { dependsOn = true; combinedAnnotation = combinedAnnotation.Meet(constraintAnnotation); } } if (dependsOn) { annotation = combinedAnnotation.Join(typeParameter1Annotation); return true; } annotation = default; return false; } void visitInterpolatedStringHandlerConstructor() { var handlerData = conversionOperand.GetInterpolatedStringHandlerData(throwOnMissing: false); if (handlerData.IsDefault) { return; } if (previousArgumentConversionResults == null) { Debug.Assert(handlerData.ArgumentPlaceholders.IsEmpty || handlerData.ArgumentPlaceholders.Single().ArgumentIndex == BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter); visitHandlerConstruction(handlerData); return; } bool addedPlaceholders = false; foreach (var placeholder in handlerData.ArgumentPlaceholders) { switch (placeholder.ArgumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter: case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: // We presume that all instance parameters were dereferenced by calling the instance method this handler was passed to. This isn't strictly // true: the handler constructor will be run before the receiver is dereferenced. However, if the dereference isn't safe, that will be a // much better error to report than a mismatched argument nullability error. case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: break; default: if (previousArgumentConversionResults.Count > placeholder.ArgumentIndex) { // We intentionally do not give a replacement bound node for this placeholder, as we do not propagate any post conditions from the constructor // to the original location of the node. This is because the nullable walker is not a true evaluation-order walker, and doing so would cause // us to miss real warnings. AddPlaceholderReplacement(placeholder, expression: null, previousArgumentConversionResults[placeholder.ArgumentIndex]); addedPlaceholders = true; } break; } } visitHandlerConstruction(handlerData); if (addedPlaceholders) { foreach (var placeholder in handlerData.ArgumentPlaceholders) { if (placeholder.ArgumentIndex < previousArgumentConversionResults.Count && placeholder.ArgumentIndex >= 0) { RemovePlaceholderReplacement(placeholder); } } } } void visitHandlerConstruction(InterpolatedStringHandlerData handlerData) { #if DEBUG bool save_completingTargetTypedExpression = _completingTargetTypedExpression; _completingTargetTypedExpression = false; #endif VisitRvalue(handlerData.Construction); #if DEBUG _completingTargetTypedExpression = save_completingTargetTypedExpression; #endif } } private TypeWithState VisitUserDefinedConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportTopLevelWarnings, bool reportRemainingWarnings, Location diagnosticLocation) { Debug.Assert(!IsConditionalState); Debug.Assert(conversionOperand != null); Debug.Assert(targetTypeWithNullability.HasType); Debug.Assert(diagnosticLocation != null); Debug.Assert(conversion.Kind == ConversionKind.ExplicitUserDefined || conversion.Kind == ConversionKind.ImplicitUserDefined); TypeSymbol targetType = targetTypeWithNullability.Type; // cf. Binder.CreateUserDefinedConversion if (!conversion.IsValid) { var resultType = TypeWithState.Create(targetType, NullableFlowState.NotNull); TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; } // operand -> conversion "from" type // May be distinct from method parameter type for Nullable<T>. operandType = VisitConversion( conversionOpt, conversionOperand, conversion.UserDefinedFromConversion, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.FromType), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt: diagnosticLocation); // Update method based on operandType: see https://github.com/dotnet/roslyn/issues/29605. // (see NullableReferenceTypesTests.ImplicitConversions_07). var method = conversion.Method; Debug.Assert(method is object); Debug.Assert(method.ParameterCount == 1); Debug.Assert(operandType.Type is object); var parameter = method.Parameters[0]; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); TypeWithState underlyingOperandType = default; bool isLiftedConversion = false; if (operandType.Type.IsNullableType() && !parameterType.IsNullableType()) { var underlyingOperandTypeWithAnnotations = operandType.Type.GetNullableUnderlyingTypeWithAnnotations(); underlyingOperandType = underlyingOperandTypeWithAnnotations.ToTypeWithState(); isLiftedConversion = parameterType.Equals(underlyingOperandTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions); } // conversion "from" type -> method parameter type NullableFlowState operandState = operandType.State; Location operandLocation = conversionOperand.Syntax.GetLocation(); _ = ClassifyAndVisitConversion( conversionOperand, parameterType, isLiftedConversion ? underlyingOperandType : operandType, useLegacyWarnings, AssignmentKind.Argument, parameterOpt: parameter, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // in the case of a lifted conversion, we assume that the call to the operator occurs only if the argument is not-null if (!isLiftedConversion && CheckDisallowedNullAssignment(operandType, parameterAnnotations, conversionOperand.Syntax.Location)) { LearnFromNonNullTest(conversionOperand, ref State); } // method parameter type -> method return type var methodReturnType = method.ReturnTypeWithAnnotations; operandType = GetLiftedReturnTypeIfNecessary(isLiftedConversion, methodReturnType, operandState); if (!isLiftedConversion || operandState.IsNotNull()) { var returnNotNull = operandState.IsNotNull() && method.ReturnNotNullIfParameterNotNull.Contains(parameter.Name); if (returnNotNull) { operandType = operandType.WithNotNullState(); } else { operandType = ApplyUnconditionalAnnotations(operandType, GetRValueAnnotations(method)); } } // method return type -> conversion "to" type // May be distinct from method return type for Nullable<T>. operandType = ClassifyAndVisitConversion( conversionOperand, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.ToType), operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // conversion "to" type -> final type // We should only pass fromExplicitCast here. Given the following example: // // class A { public static explicit operator C(A a) => throw null!; } // class C // { // void M() => var c = (C?)new A(); // } // // This final conversion from the method return type "C" to the cast type "C?" is // where we will need to ensure that this is counted as an explicit cast, so that // the resulting operandType is nullable if that was introduced via cast. operandType = ClassifyAndVisitConversion( conversionOpt ?? conversionOperand, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: conversionOpt?.ExplicitCastInCode ?? false, diagnosticLocation); LearnFromPostConditions(conversionOperand, parameterAnnotations); TrackAnalyzedNullabilityThroughConversionGroup(operandType, conversionOpt, conversionOperand); return operandType; } private void SnapshotWalkerThroughConversionGroup(BoundExpression conversionExpression, BoundExpression convertedNode) { if (_snapshotBuilderOpt is null) { return; } var conversionOpt = conversionExpression as BoundConversion; var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode && conversionOpt.Syntax.SpanStart != convertedNode.Syntax.SpanStart) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); TakeIncrementalSnapshot(conversionOpt); conversionOpt = conversionOpt.Operand as BoundConversion; } } private void TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState resultType, BoundConversion? conversionOpt, BoundExpression convertedNode) { var visitResult = new VisitResult(resultType, resultType.ToTypeWithAnnotations(compilation)); var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); visitResult = withType(visitResult, conversionOpt.Type); SetAnalyzedNullability(conversionOpt, visitResult); conversionOpt = conversionOpt.Operand as BoundConversion; } static VisitResult withType(VisitResult visitResult, TypeSymbol newType) => new VisitResult(TypeWithState.Create(newType, visitResult.RValueType.State), TypeWithAnnotations.Create(newType, visitResult.LValueType.NullableAnnotation)); } /// <summary> /// Return the return type for a lifted operator, given the nullability state of its operands. /// </summary> private TypeWithState GetLiftedReturnType(TypeWithAnnotations returnType, NullableFlowState operandState) { bool typeNeedsLifting = returnType.Type.IsNonNullableValueType(); TypeSymbol type = typeNeedsLifting ? MakeNullableOf(returnType) : returnType.Type; NullableFlowState state = returnType.ToTypeWithState().State.Join(operandState); return TypeWithState.Create(type, state); } private static TypeWithState GetNullableUnderlyingTypeIfNecessary(bool isLifted, TypeWithState typeWithState) { if (isLifted) { var type = typeWithState.Type; if (type?.IsNullableType() == true) { return type.GetNullableUnderlyingTypeWithAnnotations().ToTypeWithState(); } } return typeWithState; } private TypeWithState GetLiftedReturnTypeIfNecessary(bool isLifted, TypeWithAnnotations returnType, NullableFlowState operandState) { return isLifted ? GetLiftedReturnType(returnType, operandState) : returnType.ToTypeWithState(); } private TypeSymbol MakeNullableOf(TypeWithAnnotations underlying) { return compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(ImmutableArray.Create(underlying)); } private TypeWithState ClassifyAndVisitConversion( BoundExpression node, TypeWithAnnotations targetType, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings, bool fromExplicitCast, Location diagnosticLocation) { Debug.Assert(operandType.Type is object); Debug.Assert(diagnosticLocation != null); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyStandardConversion(operandType.Type, targetType.Type, ref discardedUseSiteInfo); if (reportWarnings && !conversion.Exists) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocation, operandType.Type, parameterOpt, targetType.Type, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocation, operandType.Type, targetType.Type); } } return VisitConversion( conversionOpt: null, conversionOperand: node, conversion, targetType, operandType, checkConversion: false, fromExplicitCast, useLegacyWarnings: useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: !fromExplicitCast && reportWarnings, diagnosticLocationOpt: diagnosticLocation); } public override BoundNode? VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { Debug.Assert(node.Type.IsDelegateType()); if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } Action<NamedTypeSymbol>? analysisCompletion; var delegateType = (NamedTypeSymbol)node.Type; switch (node.Argument) { case BoundMethodGroup group: { analysisCompletion = visitMethodGroupArgument(node, delegateType, group); } break; case BoundLambda lambda: { analysisCompletion = visitLambdaArgument(delegateType, lambda, node.WasTargetTyped); } break; case BoundExpression arg when arg.Type is { TypeKind: TypeKind.Delegate }: { analysisCompletion = visitDelegateArgument(delegateType, arg, node.WasTargetTyped); } break; default: VisitRvalue(node.Argument); analysisCompletion = null; break; } TypeWithState result = setAnalyzedNullability(node, delegateType, analysisCompletion, node.WasTargetTyped); SetResultType(node, result, updateAnalyzedNullability: false); return null; TypeWithState setAnalyzedNullability(BoundDelegateCreationExpression node, NamedTypeSymbol delegateType, Action<NamedTypeSymbol>? analysisCompletion, bool isTargetTyped) { var result = TypeWithState.Create(delegateType, NullableFlowState.NotNull); if (isTargetTyped) { setAnalyzedNullabilityAsContinuation(node, analysisCompletion); } else { Debug.Assert(analysisCompletion is null); SetAnalyzedNullability(node, result); } return result; } void setAnalyzedNullabilityAsContinuation(BoundDelegateCreationExpression node, Action<NamedTypeSymbol>? analysisCompletion) { TargetTypedAnalysisCompletion[node] = (TypeWithAnnotations resultTypeWithAnnotations) => { Debug.Assert(TypeSymbol.Equals(resultTypeWithAnnotations.Type, node.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); var delegateType = (NamedTypeSymbol)resultTypeWithAnnotations.Type; analysisCompletion?.Invoke(delegateType); return setAnalyzedNullability(node, delegateType, analysisCompletion: null, isTargetTyped: false); }; } Action<NamedTypeSymbol>? visitMethodGroupArgument(BoundDelegateCreationExpression node, NamedTypeSymbol delegateType, BoundMethodGroup group) { VisitMethodGroup(group); SetAnalyzedNullability(group, default); return analyzeMethodGroupConversion(node, delegateType, group, node.WasTargetTyped); } Action<NamedTypeSymbol>? analyzeMethodGroupConversion(BoundDelegateCreationExpression node, NamedTypeSymbol delegateType, BoundMethodGroup group, bool isTargetTyped) { if (isTargetTyped) { return analyzeMethodGroupConversionAsContinuation(node, group); } var method = node.MethodOpt; if (method is object && delegateType.DelegateInvokeMethod is { } delegateInvokeMethod) { method = CheckMethodGroupReceiverNullability(group, delegateInvokeMethod.Parameters, method, node.IsExtensionMethod); if (!group.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(group.Syntax.Location, delegateType, delegateInvokeMethod, method, node.IsExtensionMethod); } } return null; } Action<NamedTypeSymbol>? analyzeMethodGroupConversionAsContinuation(BoundDelegateCreationExpression node, BoundMethodGroup group) { return (NamedTypeSymbol delegateType) => { analyzeMethodGroupConversion(node, delegateType, group, isTargetTyped: false); }; } Action<NamedTypeSymbol>? visitLambdaArgument(NamedTypeSymbol delegateType, BoundLambda lambda, bool isTargetTyped) { SetNotNullResult(lambda); return analyzeLambdaConversion(delegateType, lambda, isTargetTyped); } Action<NamedTypeSymbol>? analyzeLambdaConversion(NamedTypeSymbol delegateType, BoundLambda lambda, bool isTargetTyped) { if (isTargetTyped) { return analyzeLambdaConversionAsContinuation(lambda); } VisitLambda(lambda, delegateType); if (!lambda.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(lambda.Symbol.DiagnosticLocation, delegateType, lambda); } return null; } Action<NamedTypeSymbol> analyzeLambdaConversionAsContinuation(BoundLambda lambda) { return (NamedTypeSymbol delegateType) => analyzeLambdaConversion(delegateType, lambda, isTargetTyped: false); } Action<NamedTypeSymbol>? visitDelegateArgument(NamedTypeSymbol delegateType, BoundExpression arg, bool isTargetTyped) { Debug.Assert(arg.Type is not null); TypeSymbol argType = arg.Type; var argTypeWithAnnotations = TypeWithAnnotations.Create(argType, NullableAnnotation.NotAnnotated); var argState = VisitRvalueWithState(arg); ReportNullableAssignmentIfNecessary(arg, argTypeWithAnnotations, argState, useLegacyWarnings: false); // Delegate creation will throw an exception if the argument is null LearnFromNonNullTest(arg, ref State); return analyzeDelegateConversion(delegateType, arg, isTargetTyped); } Action<NamedTypeSymbol>? analyzeDelegateConversion(NamedTypeSymbol delegateType, BoundExpression arg, bool isTargetTyped) { if (isTargetTyped) { return analyzeDelegateConversionAsContinuation(arg); } Debug.Assert(arg.Type is not null); TypeSymbol argType = arg.Type; if (!arg.IsSuppressed && delegateType.DelegateInvokeMethod is { } delegateInvokeMethod && argType.DelegateInvokeMethod() is { } argInvokeMethod) { ReportNullabilityMismatchWithTargetDelegate(arg.Syntax.Location, delegateType, delegateInvokeMethod, argInvokeMethod, invokedAsExtensionMethod: false); } return null; } Action<NamedTypeSymbol> analyzeDelegateConversionAsContinuation(BoundExpression arg) { return (NamedTypeSymbol delegateType) => analyzeDelegateConversion(delegateType, arg, isTargetTyped: false); } } public override BoundNode? VisitMethodGroup(BoundMethodGroup node) { Debug.Assert(!IsConditionalState); var receiverOpt = node.ReceiverOpt; if (receiverOpt != null) { VisitRvalue(receiverOpt); // Receiver nullability is checked when applying the method group conversion, // when we have a specific method, to avoid reporting null receiver warnings // for extension method delegates. Here, store the receiver state for that check. SetMethodGroupReceiverNullability(receiverOpt, ResultType); } SetNotNullResult(node); return null; } private bool TryGetMethodGroupReceiverNullability([NotNullWhen(true)] BoundExpression? receiverOpt, out TypeWithState type) { if (receiverOpt != null && _methodGroupReceiverMapOpt != null && _methodGroupReceiverMapOpt.TryGetValue(receiverOpt, out type)) { return true; } else { type = default; return false; } } private void SetMethodGroupReceiverNullability(BoundExpression receiver, TypeWithState type) { _methodGroupReceiverMapOpt ??= PooledDictionary<BoundExpression, TypeWithState>.GetInstance(); _methodGroupReceiverMapOpt[receiver] = type; } private MethodSymbol CheckMethodGroupReceiverNullability(BoundMethodGroup group, ImmutableArray<ParameterSymbol> parameters, MethodSymbol method, bool invokedAsExtensionMethod) { var receiverOpt = group.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { var syntax = group.Syntax; if (!invokedAsExtensionMethod) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } if (method.IsGenericMethod && HasImplicitTypeArguments(group.Syntax)) { var arguments = ArrayBuilder<BoundExpression>.GetInstance(); if (invokedAsExtensionMethod) { arguments.Add(CreatePlaceholderIfNecessary(receiverOpt, receiverType.ToTypeWithAnnotations(compilation))); } // Create placeholders for the arguments. (See Conversions.GetDelegateArguments() // which is used for that purpose in initial binding.) foreach (var parameter in parameters) { var parameterType = parameter.TypeWithAnnotations; arguments.Add(new BoundExpressionWithNullability(syntax, new BoundParameter(syntax, parameter), parameterType.NullableAnnotation, parameterType.Type)); } Debug.Assert(_binder is object); method = InferMethodTypeArguments(method, arguments.ToImmutableAndFree(), argumentRefKindsOpt: default, argsToParamsOpt: default, expanded: false); } if (invokedAsExtensionMethod) { CheckExtensionMethodThisNullability(receiverOpt, Conversion.Identity, method.Parameters[0], receiverType); } else { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } if (ConstraintsHelper.RequiresChecking(method)) { CheckMethodConstraints(syntax, method); } } return method; } public override BoundNode? VisitLambda(BoundLambda node) { // Note: actual lambda analysis happens after this call (primarily in VisitConversion). // Here we just indicate that a lambda expression produces a non-null value. SetNotNullResult(node); return null; } private void VisitLambda(BoundLambda node, NamedTypeSymbol? delegateTypeOpt, Optional<LocalState> initialState = default) { Debug.Assert(delegateTypeOpt?.IsDelegateType() != false); var delegateInvokeMethod = delegateTypeOpt?.DelegateInvokeMethod; UseDelegateInvokeParameterAndReturnTypes(node, delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); if (useDelegateInvokeParameterTypes && _snapshotBuilderOpt is object) { SetUpdatedSymbol(node, node.Symbol, delegateTypeOpt!); } AnalyzeLocalFunctionOrLambda( node, node.Symbol, initialState.HasValue ? initialState.Value : State.Clone(), delegateInvokeMethod, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType); } private static void UseDelegateInvokeParameterAndReturnTypes(BoundLambda lambda, MethodSymbol? delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType) { if (delegateInvokeMethod is null) { useDelegateInvokeParameterTypes = false; useDelegateInvokeReturnType = false; } else { var unboundLambda = lambda.UnboundLambda; useDelegateInvokeParameterTypes = !unboundLambda.HasExplicitlyTypedParameterList; useDelegateInvokeReturnType = !unboundLambda.HasExplicitReturnType(out _, out _); } } public override BoundNode? VisitUnboundLambda(UnboundLambda node) { // The presence of this node suggests an error was detected in an earlier phase. // Analyze the body to report any additional warnings. var lambda = node.BindForErrorRecovery(); VisitLambda(lambda, delegateTypeOpt: null); SetNotNullResult(node); return null; } public override BoundNode? VisitThisReference(BoundThisReference node) { VisitThisOrBaseReference(node); return null; } private void VisitThisOrBaseReference(BoundExpression node) { var rvalueResult = TypeWithState.Create(node.Type, NullableFlowState.NotNull); var lvalueResult = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); SetResult(node, rvalueResult, lvalueResult); } public override BoundNode? VisitParameter(BoundParameter node) { var parameter = node.ParameterSymbol; int slot = GetOrCreateSlot(parameter); var parameterType = GetDeclaredParameterResult(parameter); var typeWithState = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations); SetResult(node, GetAdjustedResult(typeWithState, slot), parameterType); return null; } public override BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) { Debug.Assert(!IsConditionalState); var left = node.Left; switch (left) { // when binding initializers, we treat assignments to auto-properties or field-like events as direct assignments to the underlying field. // in order to track member state based on these initializers, we need to see the assignment in terms of the associated member case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: PropertySymbol autoProperty } } fieldAccess: left = new BoundPropertyAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, autoProperty, LookupResultKind.Viable, autoProperty.Type, fieldAccess.HasErrors); break; case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: EventSymbol @event } } fieldAccess: left = new BoundEventAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, @event, isUsableAsField: true, LookupResultKind.Viable, @event.Type, fieldAccess.HasErrors); break; } var right = node.Right; VisitLValue(left); // we may enter a conditional state for error scenarios on the LHS. Unsplit(); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (left.Kind == BoundKind.EventAccess && ((BoundEventAccess)left).EventSymbol.IsWindowsRuntimeEvent) { // Event assignment is a call to an Add method. (Note that assignment // of non-field-like events uses BoundEventAssignmentOperator // rather than BoundAssignmentOperator.) VisitRvalue(right); SetNotNullResult(node); } else { TypeWithState rightState; if (!node.IsRef) { var discarded = left is BoundDiscardExpression; rightState = VisitOptionalImplicitConversion(right, targetTypeOpt: discarded ? default : leftLValueType, UseLegacyWarnings(left, leftLValueType), trackMembers: true, AssignmentKind.Assignment); Unsplit(); } else { rightState = VisitRefExpression(right, leftLValueType); } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(rightState, leftAnnotations, right.Syntax.Location); AdjustSetValue(left, ref rightState); TrackNullableStateForAssignment(right, leftLValueType, MakeSlot(left), rightState, MakeSlot(right)); if (left is BoundDiscardExpression) { var lvalueType = rightState.ToTypeWithAnnotations(compilation); SetResult(left, rightState, lvalueType, isLvalue: true); SetResult(node, rightState, lvalueType); } else { SetResult(node, TypeWithState.Create(leftLValueType.Type, rightState.State), leftLValueType); } } return null; } private bool IsPropertyOutputMoreStrictThanInput(PropertySymbol property) { var type = property.TypeWithAnnotations; var annotations = IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : property.GetFlowAnalysisAnnotations(); var lValueType = ApplyLValueAnnotations(type, annotations); if (lValueType.NullableAnnotation.IsOblivious() || !lValueType.CanBeAssignedNull) { return false; } var rValueType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), annotations); return rValueType.IsNotNull; } /// <summary> /// When the allowed output of a property/indexer is not-null but the allowed input is maybe-null, we store a not-null value instead. /// This way, assignment of a legal input value results in a legal output value. /// This adjustment doesn't apply to oblivious properties/indexers. /// </summary> private void AdjustSetValue(BoundExpression left, ref TypeWithState rightState) { var property = left switch { BoundPropertyAccess propAccess => propAccess.PropertySymbol, BoundIndexerAccess indexerAccess => indexerAccess.Indexer, _ => null }; if (property is not null && IsPropertyOutputMoreStrictThanInput(property)) { rightState = rightState.WithNotNullState(); } } private FlowAnalysisAnnotations GetLValueAnnotations(BoundExpression expr) { Debug.Assert(expr is not BoundObjectInitializerMember); // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = expr switch { BoundPropertyAccess property => property.PropertySymbol.GetFlowAnalysisAnnotations(), BoundIndexerAccess indexer => indexer.Indexer.GetFlowAnalysisAnnotations(), BoundFieldAccess field => GetFieldAnnotations(field.FieldSymbol), BoundParameter { ParameterSymbol: ParameterSymbol parameter } => ToInwardAnnotations(GetParameterAnnotations(parameter) & ~FlowAnalysisAnnotations.NotNull), // NotNull is enforced upon method exit _ => FlowAnalysisAnnotations.None }; return annotations & (FlowAnalysisAnnotations.DisallowNull | FlowAnalysisAnnotations.AllowNull); } private static FlowAnalysisAnnotations GetFieldAnnotations(FieldSymbol field) { return field.AssociatedSymbol is PropertySymbol property ? property.GetFlowAnalysisAnnotations() : field.FlowAnalysisAnnotations; } private FlowAnalysisAnnotations GetObjectInitializerMemberLValueAnnotations(Symbol memberSymbol) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = memberSymbol switch { PropertySymbol prop => prop.GetFlowAnalysisAnnotations(), FieldSymbol field => GetFieldAnnotations(field), _ => FlowAnalysisAnnotations.None }; return annotations & (FlowAnalysisAnnotations.DisallowNull | FlowAnalysisAnnotations.AllowNull); } private static FlowAnalysisAnnotations ToInwardAnnotations(FlowAnalysisAnnotations outwardAnnotations) { var annotations = FlowAnalysisAnnotations.None; if ((outwardAnnotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen count as MaybeNull annotations |= FlowAnalysisAnnotations.AllowNull; } if ((outwardAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNullWhenTrue and NotNullWhenFalse don't count on their own. Only NotNull (ie. both flags) matters. annotations |= FlowAnalysisAnnotations.DisallowNull; } return annotations; } private static bool UseLegacyWarnings(BoundExpression expr, TypeWithAnnotations exprType) { switch (expr.Kind) { case BoundKind.Local: return expr.GetRefKind() == RefKind.None; case BoundKind.Parameter: RefKind kind = ((BoundParameter)expr).ParameterSymbol.RefKind; return kind == RefKind.None; default: return false; } } public override BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { return VisitDeconstructionAssignmentOperator(node, rightResultOpt: null); } private BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node, TypeWithState? rightResultOpt) { var previousDisableNullabilityAnalysis = _disableNullabilityAnalysis; _disableNullabilityAnalysis = true; var left = node.Left; var right = node.Right; var variables = GetDeconstructionAssignmentVariables(left); if (node.HasErrors) { // In the case of errors, simply visit the right as an r-value to update // any nullability state even though deconstruction is skipped. VisitRvalue(right.Operand); } else { VisitDeconstructionArguments(variables, right.Conversion, right.Operand, rightResultOpt); } variables.FreeAll(v => v.NestedVariables); // https://github.com/dotnet/roslyn/issues/33011: Result type should be inferred and the constraints should // be re-verified. Even though the standard tuple type has no constraints we support that scenario. Constraints_78 // has a test for this case that should start failing when this is fixed. SetNotNullResult(node); _disableNullabilityAnalysis = previousDisableNullabilityAnalysis; return null; } private void VisitDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt = null) { Debug.Assert(conversion.Kind == ConversionKind.Deconstruction); if (!conversion.DeconstructionInfo.IsDefault) { VisitDeconstructMethodArguments(variables, conversion, right, rightResultOpt); } else { VisitTupleDeconstructionArguments(variables, conversion.DeconstructConversionInfo, right, rightResultOpt); } } private void VisitDeconstructMethodArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt) { VisitRvalue(right); // If we were passed an explicit right result, use that rather than the visited result if (rightResultOpt.HasValue) { SetResultType(right, rightResultOpt.Value); } var rightResult = ResultType; var invocation = conversion.DeconstructionInfo.Invocation as BoundCall; var deconstructMethod = invocation?.Method; if (deconstructMethod is object) { Debug.Assert(invocation is object); Debug.Assert(rightResult.Type is object); int n = variables.Count; if (!invocation.InvokedAsExtensionMethod) { _ = CheckPossibleNullReceiver(right); // update the deconstruct method with any inferred type parameters of the containing type if (deconstructMethod.OriginalDefinition != deconstructMethod) { deconstructMethod = (MethodSymbol)AsMemberOfType(rightResult.Type, deconstructMethod); } } else { if (deconstructMethod.IsGenericMethod) { // re-infer the deconstruct parameters based on the 'this' parameter ArrayBuilder<BoundExpression> placeholderArgs = ArrayBuilder<BoundExpression>.GetInstance(n + 1); placeholderArgs.Add(CreatePlaceholderIfNecessary(right, rightResult.ToTypeWithAnnotations(compilation))); for (int i = 0; i < n; i++) { placeholderArgs.Add(new BoundExpressionWithNullability(variables[i].Expression.Syntax, variables[i].Expression, NullableAnnotation.Oblivious, conversion.DeconstructionInfo.OutputPlaceholders[i].Type)); } deconstructMethod = InferMethodTypeArguments(deconstructMethod, placeholderArgs.ToImmutableAndFree(), invocation.ArgumentRefKindsOpt, invocation.ArgsToParamsOpt, invocation.Expanded); // check the constraints remain valid with the re-inferred parameter types if (ConstraintsHelper.RequiresChecking(deconstructMethod)) { CheckMethodConstraints(invocation.Syntax, deconstructMethod); } } } var parameters = deconstructMethod.Parameters; int offset = invocation.InvokedAsExtensionMethod ? 1 : 0; Debug.Assert(parameters.Length - offset == n); if (invocation.InvokedAsExtensionMethod) { // Check nullability for `this` parameter var argConversion = RemoveConversion(invocation.Arguments[0], includeExplicitConversions: false).conversion; CheckExtensionMethodThisNullability(right, argConversion, deconstructMethod.Parameters[0], rightResult); } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var (placeholder, placeholderConversion) = conversion.DeconstructConversionInfo[i]; var underlyingConversion = BoundNode.GetConversion(placeholderConversion, placeholder); var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { var nestedRight = CreatePlaceholderIfNecessary(invocation.Arguments[i + offset], parameter.TypeWithAnnotations); VisitDeconstructionArguments(nestedVariables, underlyingConversion, right: nestedRight); } else { VisitArgumentConversionAndInboundAssignmentsAndPreConditions(conversionOpt: null, variable.Expression, underlyingConversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), conversionResultsBuilder: null, extensionMethodThisArgument: false); } } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var nestedVariables = variable.NestedVariables; if (nestedVariables == null) { VisitArgumentOutboundAssignmentsAndPostConditions( variable.Expression, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetRValueAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), notNullParametersOpt: null, compareExchangeInfoOpt: default); } } } } private void VisitTupleDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, ImmutableArray<(BoundValuePlaceholder? placeholder, BoundExpression? conversion)> deconstructConversionInfo, BoundExpression right, TypeWithState? rightResultOpt) { int n = variables.Count; var rightParts = GetDeconstructionRightParts(right, rightResultOpt); Debug.Assert(rightParts.Length == n); for (int i = 0; i < n; i++) { var variable = variables[i]; var (placeholder, placeholderConversion) = deconstructConversionInfo[i]; var underlyingConversion = BoundNode.GetConversion(placeholderConversion, placeholder); var rightPart = rightParts[i]; var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { VisitDeconstructionArguments(nestedVariables, underlyingConversion, rightPart); } else { var lvalueType = variable.Type; var leftAnnotations = GetLValueAnnotations(variable.Expression); lvalueType = ApplyLValueAnnotations(lvalueType, leftAnnotations); TypeWithState operandType; TypeWithState valueType; int valueSlot; if (underlyingConversion.IsIdentity) { if (variable.Expression is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } local) { // when the LHS is a var declaration, we can just visit the right part to infer the type valueType = operandType = VisitRvalueWithState(rightPart); _variables.SetType(local.LocalSymbol, operandType.ToAnnotatedTypeWithAnnotations(compilation)); } else { operandType = default; valueType = VisitOptionalImplicitConversion(rightPart, lvalueType, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); Unsplit(); } valueSlot = MakeSlot(rightPart); } else { operandType = VisitRvalueWithState(rightPart); valueType = VisitConversion( conversionOpt: null, rightPart, underlyingConversion, lvalueType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: true, AssignmentKind.Assignment, reportTopLevelWarnings: true, reportRemainingWarnings: true, trackMembers: false); valueSlot = -1; } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(valueType, leftAnnotations, right.Syntax.Location); int targetSlot = MakeSlot(variable.Expression); AdjustSetValue(variable.Expression, ref valueType); TrackNullableStateForAssignment(rightPart, lvalueType, targetSlot, valueType, valueSlot); // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (targetSlot > 0 && underlyingConversion.Kind == ConversionKind.ImplicitNullable && AreNullableAndUnderlyingTypes(lvalueType.Type, operandType.Type, out TypeWithAnnotations underlyingType)) { valueSlot = MakeSlot(rightPart); if (valueSlot > 0) { var valueBeforeNullableWrapping = TypeWithState.Create(underlyingType.Type, NullableFlowState.NotNull); TrackNullableStateOfNullableValue(targetSlot, lvalueType.Type, rightPart, valueBeforeNullableWrapping, valueSlot); } } } } } private readonly struct DeconstructionVariable { internal readonly BoundExpression Expression; internal readonly TypeWithAnnotations Type; internal readonly ArrayBuilder<DeconstructionVariable>? NestedVariables; internal DeconstructionVariable(BoundExpression expression, TypeWithAnnotations type) { Expression = expression; Type = type; NestedVariables = null; } internal DeconstructionVariable(BoundExpression expression, ArrayBuilder<DeconstructionVariable> nestedVariables) { Expression = expression; Type = default; NestedVariables = nestedVariables; } } private ArrayBuilder<DeconstructionVariable> GetDeconstructionAssignmentVariables(BoundTupleExpression tuple) { var arguments = tuple.Arguments; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(arguments.Length); foreach (var argument in arguments) { builder.Add(getDeconstructionAssignmentVariable(argument)); } return builder; DeconstructionVariable getDeconstructionAssignmentVariable(BoundExpression expr) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return new DeconstructionVariable(expr, GetDeconstructionAssignmentVariables((BoundTupleExpression)expr)); default: VisitLValue(expr); return new DeconstructionVariable(expr, LvalueResultType); } } } /// <summary> /// Return the sub-expressions for the righthand side of a deconstruction /// assignment. cf. LocalRewriter.GetRightParts. /// </summary> private ImmutableArray<BoundExpression> GetDeconstructionRightParts(BoundExpression expr, TypeWithState? rightResultOpt) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return ((BoundTupleExpression)expr).Arguments; case BoundKind.Conversion: { var conv = (BoundConversion)expr; switch (conv.ConversionKind) { case ConversionKind.Identity: case ConversionKind.ImplicitTupleLiteral: return GetDeconstructionRightParts(conv.Operand, null); } } break; } if (rightResultOpt is { } rightResult) { expr = CreatePlaceholderIfNecessary(expr, rightResult.ToTypeWithAnnotations(compilation)); } if (expr.Type is NamedTypeSymbol { IsTupleType: true } tupleType) { // https://github.com/dotnet/roslyn/issues/33011: Should include conversion.UnderlyingConversions[i]. // For instance, Boxing conversions (see Deconstruction_ImplicitBoxingConversion_02) and // ImplicitNullable conversions (see Deconstruction_ImplicitNullableConversion_02). var fields = tupleType.TupleElements; return fields.SelectAsArray((f, e) => (BoundExpression)new BoundFieldAccess(e.Syntax, e, f, constantValueOpt: null), expr); } throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitIncrementOperator(BoundIncrementOperator node) { Debug.Assert(!IsConditionalState); var operandType = VisitRvalueWithState(node.Operand); var operandLvalue = LvalueResultType; bool setResult = false; if (this.State.Reachable) { // https://github.com/dotnet/roslyn/issues/29961 Update increment method based on operand type. MethodSymbol? incrementOperator = (node.OperatorKind.IsUserDefined() && node.MethodOpt?.ParameterCount == 1) ? node.MethodOpt : null; TypeWithAnnotations targetTypeOfOperandConversion; AssignmentKind assignmentKind = AssignmentKind.Assignment; ParameterSymbol? parameter = null; // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 // https://github.com/dotnet/roslyn/issues/29961 Update conversion method based on operand type. if (node.OperandConversion is BoundConversion { Conversion: var operandConversion } && operandConversion.IsUserDefined && operandConversion.Method?.ParameterCount == 1) { targetTypeOfOperandConversion = operandConversion.Method.ReturnTypeWithAnnotations; } else if (incrementOperator is object) { targetTypeOfOperandConversion = incrementOperator.Parameters[0].TypeWithAnnotations; assignmentKind = AssignmentKind.Argument; parameter = incrementOperator.Parameters[0]; } else { // Either a built-in increment, or an error case. targetTypeOfOperandConversion = default; } TypeWithState resultOfOperandConversionType; if (targetTypeOfOperandConversion.HasType) { // https://github.com/dotnet/roslyn/issues/29961 Should something special be done for targetTypeOfOperandConversion for lifted case? resultOfOperandConversionType = VisitConversion( conversionOpt: null, node.Operand, BoundNode.GetConversion(node.OperandConversion, node.OperandPlaceholder), targetTypeOfOperandConversion, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind, parameter, reportTopLevelWarnings: true, reportRemainingWarnings: true); } else { resultOfOperandConversionType = operandType; } TypeWithState resultOfIncrementType; if (incrementOperator is null) { resultOfIncrementType = resultOfOperandConversionType; } else { resultOfIncrementType = incrementOperator.ReturnTypeWithAnnotations.ToTypeWithState(); } var operandTypeWithAnnotations = operandType.ToTypeWithAnnotations(compilation); resultOfIncrementType = VisitConversion( conversionOpt: null, node, BoundNode.GetConversion(node.ResultConversion, node.ResultPlaceholder), operandTypeWithAnnotations, resultOfIncrementType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // https://github.com/dotnet/roslyn/issues/29961 Check node.Type.IsErrorType() instead? if (!node.HasErrors) { var op = node.OperatorKind.Operator(); TypeWithState resultType = (op == UnaryOperatorKind.PrefixIncrement || op == UnaryOperatorKind.PrefixDecrement) ? resultOfIncrementType : operandType; SetResultType(node, resultType); setResult = true; TrackNullableStateForAssignment(node, targetType: operandLvalue, targetSlot: MakeSlot(node.Operand), valueType: resultOfIncrementType); } } if (!setResult) { SetNotNullResult(node); } return null; } public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { var left = node.Left; var right = node.Right; Visit(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = declaredType; TypeWithState leftResultType = ResultType; Debug.Assert(!IsConditionalState); TypeWithState leftOnRightType = GetAdjustedResult(leftResultType, MakeSlot(node.Left)); // https://github.com/dotnet/roslyn/issues/29962 Update operator based on inferred argument types. if ((object)node.Operator.LeftType != null) { // https://github.com/dotnet/roslyn/issues/29962 Ignoring top-level nullability of operator left parameter. leftOnRightType = VisitConversion( conversionOpt: null, node.Left, BoundNode.GetConversion(node.LeftConversion, node.LeftPlaceholder), TypeWithAnnotations.Create(node.Operator.LeftType), leftOnRightType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: true); } else { leftOnRightType = default; } TypeWithState resultType; TypeWithState rightType = VisitRvalueWithState(right); if ((object)node.Operator.ReturnType != null) { if (node.Operator.Kind.IsUserDefined() && (object)node.Operator.Method != null && node.Operator.Method.ParameterCount == 2) { MethodSymbol method = node.Operator.Method; VisitArguments(node, ImmutableArray.Create(node.Left, right), method.ParameterRefKinds, method.Parameters, argsToParamsOpt: default, defaultArguments: default, expanded: true, invokedAsExtensionMethod: false, method); } resultType = InferResultNullability(node.Operator.Kind, node.Operator.Method, node.Operator.ReturnType, leftOnRightType, rightType); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(node.Left); leftLValueType = ApplyLValueAnnotations(leftLValueType, leftAnnotations); resultType = VisitConversion( conversionOpt: null, node, BoundNode.GetConversion(node.FinalConversion, node.FinalPlaceholder), leftLValueType, resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, leftAnnotations, node.Syntax.Location); } else { resultType = TypeWithState.Create(node.Type, NullableFlowState.NotNull); } AdjustSetValue(left, ref resultType); TrackNullableStateForAssignment(node, leftLValueType, MakeSlot(node.Left), resultType); SetResultType(node, resultType); return null; } public override BoundNode? VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) { var initializer = node.Expression; if (initializer.Kind == BoundKind.AddressOfOperator) { initializer = ((BoundAddressOfOperator)initializer).Operand; } VisitRvalue(initializer); if (node.Expression.Kind == BoundKind.AddressOfOperator) { SetResultType(node.Expression, TypeWithState.Create(node.Expression.Type, ResultType.State)); } SetNotNullResult(node); return null; } public override BoundNode? VisitAddressOfOperator(BoundAddressOfOperator node) { Visit(node.Operand); SetNotNullResult(node); return null; } private void ReportArgumentWarnings(BoundExpression argument, TypeWithState argumentType, ParameterSymbol parameter) { var paramType = parameter.TypeWithAnnotations; ReportNullableAssignmentIfNecessary(argument, paramType, argumentType, useLegacyWarnings: false, AssignmentKind.Argument, parameterOpt: parameter); if (argumentType.Type is { } argType && IsNullabilityMismatch(paramType.Type, argType)) { ReportNullabilityMismatchInArgument(argument.Syntax, argType, parameter, paramType.Type, forOutput: false); } } private void ReportNullabilityMismatchInRefArgument(BoundExpression argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, argument.Syntax, argumentType, parameterType, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter)); } /// <summary> /// Report warning passing argument where nested nullability does not match /// parameter (e.g.: calling `void F(object[] o)` with `F(new[] { maybeNull })`). /// </summary> private void ReportNullabilityMismatchInArgument(SyntaxNode argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType, bool forOutput) { ReportNullabilityMismatchInArgument(argument.GetLocation(), argumentType, parameter, parameterType, forOutput); } private void ReportNullabilityMismatchInArgument(Location argumentLocation, TypeSymbol argumentType, ParameterSymbol? parameterOpt, TypeSymbol parameterType, bool forOutput) { ReportDiagnostic(forOutput ? ErrorCode.WRN_NullabilityMismatchInArgumentForOutput : ErrorCode.WRN_NullabilityMismatchInArgument, argumentLocation, argumentType, parameterOpt?.Type.IsNonNullableValueType() == true && parameterType.IsNullableType() ? parameterOpt.Type : parameterType, // Compensate for operator lifting GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); } private TypeWithAnnotations GetDeclaredLocalResult(LocalSymbol local) { return _variables.TryGetType(local, out TypeWithAnnotations type) ? type : local.TypeWithAnnotations; } private TypeWithAnnotations GetDeclaredParameterResult(ParameterSymbol parameter) { return _variables.TryGetType(parameter, out TypeWithAnnotations type) ? type : parameter.TypeWithAnnotations; } public override BoundNode? VisitBaseReference(BoundBaseReference node) { VisitThisOrBaseReference(node); return null; } public override BoundNode? VisitFieldAccess(BoundFieldAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.FieldSymbol); SplitIfBooleanConstant(node); SetUpdatedSymbol(node, node.FieldSymbol, updatedSymbol); return null; } public override BoundNode? VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; var updatedMember = VisitMemberAccess(node, node.ReceiverOpt, property); if (!IsAnalyzingAttribute) { if (_expressionIsRead) { ApplyMemberPostConditions(node.ReceiverOpt, property.GetMethod); } else { ApplyMemberPostConditions(node.ReceiverOpt, property.SetMethod); } } SetUpdatedSymbol(node, property, updatedMember); return null; } public override BoundNode? VisitIndexerAccess(BoundIndexerAccess node) { var receiverOpt = node.ReceiverOpt; var receiverType = VisitRvalueWithState(receiverOpt).Type; // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); var indexer = node.Indexer; if (receiverType is object) { // Update indexer based on inferred receiver type. indexer = (PropertySymbol)AsMemberOfType(receiverType, indexer); } VisitArguments(node, node.Arguments, node.ArgumentRefKindsOpt, indexer, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded); var resultType = ApplyUnconditionalAnnotations(indexer.TypeWithAnnotations.ToTypeWithState(), GetRValueAnnotations(indexer)); SetResult(node, resultType, indexer.TypeWithAnnotations); SetUpdatedSymbol(node, node.Indexer, indexer); return null; } public override BoundNode? VisitImplicitIndexerAccess(BoundImplicitIndexerAccess node) { VisitRvalue(node.Receiver); var receiverResult = _visitResult; VisitRvalue(node.Argument); AddPlaceholderReplacement(node.ReceiverPlaceholder, node.Receiver, receiverResult); VisitRvalue(node.IndexerOrSliceAccess); RemovePlaceholderReplacement(node.ReceiverPlaceholder); SetResult(node, ResultType, LvalueResultType); return null; } public override BoundNode? VisitImplicitIndexerValuePlaceholder(BoundImplicitIndexerValuePlaceholder node) { // These placeholders don't need to be replaced because we know they are always not-null AssertPlaceholderAllowedWithoutRegistration(node); SetNotNullResult(node); return null; } public override BoundNode? VisitImplicitIndexerReceiverPlaceholder(BoundImplicitIndexerReceiverPlaceholder node) { VisitPlaceholderWithReplacement(node); return null; } public override BoundNode? VisitEventAccess(BoundEventAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.EventSymbol); SetUpdatedSymbol(node, node.EventSymbol, updatedSymbol); return null; } private Symbol VisitMemberAccess(BoundExpression node, BoundExpression? receiverOpt, Symbol member) { Debug.Assert(!IsConditionalState); var receiverType = (receiverOpt != null) ? VisitRvalueWithState(receiverOpt) : default; SpecialMember? nullableOfTMember = null; if (member.RequiresInstanceReceiver()) { member = AsMemberOfType(receiverType.Type, member); nullableOfTMember = GetNullableOfTMember(member); // https://github.com/dotnet/roslyn/issues/30598: For l-values, mark receiver as not null // after RHS has been visited, and only if the receiver has not changed. bool skipReceiverNullCheck = nullableOfTMember != SpecialMember.System_Nullable_T_get_Value; _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType: !skipReceiverNullCheck); } var type = member.GetTypeOrReturnType(); var memberAnnotations = GetRValueAnnotations(member); var resultType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), memberAnnotations); // We are supposed to track information for the node. Use whatever we managed to // accumulate so far. if (PossiblyNullableType(resultType.Type)) { int slot = MakeMemberSlot(receiverOpt, member); if (this.State.HasValue(slot)) { var state = this.State[slot]; resultType = TypeWithState.Create(resultType.Type, state); } } Debug.Assert(!IsConditionalState); if (nullableOfTMember == SpecialMember.System_Nullable_T_get_HasValue && !(receiverOpt is null)) { int containingSlot = MakeSlot(receiverOpt); if (containingSlot > 0) { Split(); this.StateWhenTrue[containingSlot] = NullableFlowState.NotNull; } } SetResult(node, resultType, type); return member; } private SpecialMember? GetNullableOfTMember(Symbol member) { if (member.Kind == SymbolKind.Property) { var getMethod = ((PropertySymbol)member.OriginalDefinition).GetMethod; if ((object)getMethod != null && getMethod.ContainingType.SpecialType == SpecialType.System_Nullable_T) { if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { return SpecialMember.System_Nullable_T_get_Value; } if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_HasValue)) { return SpecialMember.System_Nullable_T_get_HasValue; } } } return null; } private int GetNullableOfTValueSlot(TypeSymbol containingType, int containingSlot, out Symbol? valueProperty, bool forceSlotEvenIfEmpty = false) { Debug.Assert(containingType.IsNullableType()); Debug.Assert(TypeSymbol.Equals(NominalSlotType(containingSlot), containingType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); var getValue = (MethodSymbol)compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value); valueProperty = getValue?.AsMember((NamedTypeSymbol)containingType)?.AssociatedSymbol; return (valueProperty is null) ? -1 : GetOrCreateSlot(valueProperty, containingSlot, forceSlotEvenIfEmpty: forceSlotEvenIfEmpty); } protected override void VisitForEachExpression(BoundForEachStatement node) { if (node.Expression.Kind != BoundKind.Conversion) { // If we're in this scenario, there was a binding error, and we should suppress any further warnings. Debug.Assert(node.HasErrors); VisitRvalue(node.Expression); return; } var (expr, conversion) = RemoveConversion(node.Expression, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(node.Expression, expr); // There are 7 ways that a foreach can be created: // 1. The collection type is an array type. For this, initial binding will generate an implicit reference conversion to // IEnumerable, and we do not need to do any reinferring of enumerators here. // 2. The collection type is dynamic. For this we do the same as 1. // 3. The collection type implements the GetEnumerator pattern. For this, there is an identity conversion. Because // this identity conversion uses nested types from initial binding, we cannot trust them and must instead use // the type of the expression returned from VisitResult to reinfer the enumerator information. // 4. The collection type implements IEnumerable<T>. Only a few cases can hit this without being caught by number 3, // such as a type with a private implementation of IEnumerable<T>, or a type parameter constrained to that type. // In these cases, there will be an implicit conversion to IEnumerable<T>, but this will use types from // initial binding. For this scenario, we need to look through the list of implemented interfaces on the type and // find the version of IEnumerable<T> that it has after nullable analysis, as type substitution could have changed // nested nullability of type parameters. See ForEach_22 for a concrete example of this. // 5. The collection type implements IEnumerable (non-generic). Because this version isn't generic, we don't need to // do any reinference, and the existing conversion can stand as is. // 6. The target framework's System.String doesn't implement IEnumerable. This is a compat case: System.String normally // does implement IEnumerable, but there are certain target frameworks where this isn't the case. The compiler will // still emit code for foreach in these scenarios. // 7. The collection type implements the GetEnumerator pattern via an extension GetEnumerator. For this, there will be // conversion to the parameter of the extension method. // 8. Some binding error occurred, and some other error has already been reported. Usually this doesn't have any kind // of conversion on top, but if there was an explicit conversion in code then we could get past the initial check // for a BoundConversion node. var resultTypeWithState = VisitRvalueWithState(expr); var resultType = resultTypeWithState.Type; Debug.Assert(resultType is object); SetAnalyzedNullability(expr, _visitResult); TypeWithAnnotations targetTypeWithAnnotations; MethodSymbol? reinferredGetEnumeratorMethod = null; if (node.EnumeratorInfoOpt?.GetEnumeratorInfo is { Method: { IsExtensionMethod: true, Parameters: var parameters } } enumeratorMethodInfo) { // this is case 7 // We do not need to do this same analysis for non-extension methods because they do not have generic parameters that // can be inferred from usage like extension methods can. We don't warn about default arguments at the call site, so // there's nothing that can be learned from the non-extension case. var (method, results, _) = VisitArguments( node, enumeratorMethodInfo.Arguments, refKindsOpt: default, parameters, argsToParamsOpt: enumeratorMethodInfo.ArgsToParamsOpt, defaultArguments: enumeratorMethodInfo.DefaultArguments, expanded: false, invokedAsExtensionMethod: true, enumeratorMethodInfo.Method); targetTypeWithAnnotations = results[0].LValueType; reinferredGetEnumeratorMethod = method; } else if (conversion.IsIdentity || (conversion.Kind == ConversionKind.ExplicitReference && resultType.SpecialType == SpecialType.System_String)) { // This is case 3 or 6. targetTypeWithAnnotations = resultTypeWithState.ToTypeWithAnnotations(compilation); } else if (conversion.IsImplicit) { bool isAsync = node.AwaitOpt != null; if (node.Expression.Type!.SpecialType == SpecialType.System_Collections_IEnumerable) { // If this is a conversion to IEnumerable (non-generic), nothing to do. This is cases 1, 2, and 5. targetTypeWithAnnotations = TypeWithAnnotations.Create(node.Expression.Type); } else if (ForEachLoopBinder.IsIEnumerableT(node.Expression.Type.OriginalDefinition, isAsync, compilation)) { // This is case 4. We need to look for the IEnumerable<T> that this reinferred expression implements, // so that we pick up any nested type substitutions that could have occurred. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; targetTypeWithAnnotations = TypeWithAnnotations.Create(ForEachLoopBinder.GetIEnumerableOfT(resultType, isAsync, compilation, ref discardedUseSiteInfo, out bool foundMultiple)); Debug.Assert(!foundMultiple); Debug.Assert(targetTypeWithAnnotations.HasType); } else { // This is case 8. There was not a successful binding, as a successful binding will _always_ generate one of the // above conversions. Just return, as we want to suppress further errors. return; } } else { // This is also case 8. return; } var convertedResult = VisitConversion( GetConversionIfApplicable(node.Expression, expr), expr, conversion, targetTypeWithAnnotations, resultTypeWithState, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); bool reportedDiagnostic = node.EnumeratorInfoOpt?.GetEnumeratorInfo.Method is { IsExtensionMethod: true } ? false : CheckPossibleNullReceiver(expr); SetAnalyzedNullability(node.Expression, new VisitResult(convertedResult, convertedResult.ToTypeWithAnnotations(compilation))); TypeWithState currentPropertyGetterTypeWithState; if (node.EnumeratorInfoOpt is null) { currentPropertyGetterTypeWithState = default; } else if (resultType is ArrayTypeSymbol arrayType) { // Even though arrays use the IEnumerator pattern, we use the array element type as the foreach target type, so // directly get our source type from there instead of doing method reinference. currentPropertyGetterTypeWithState = arrayType.ElementTypeWithAnnotations.ToTypeWithState(); } else if (resultType.SpecialType == SpecialType.System_String) { // There are frameworks where System.String does not implement IEnumerable, but we still lower it to a for loop // using the indexer over the individual characters anyway. So the type must be not annotated char. currentPropertyGetterTypeWithState = TypeWithAnnotations.Create(node.EnumeratorInfoOpt.ElementType, NullableAnnotation.NotAnnotated).ToTypeWithState(); } else { // Reinfer the return type of the node.Expression.GetEnumerator().Current property, so that if // the collection changed nested generic types we pick up those changes. reinferredGetEnumeratorMethod ??= (MethodSymbol)AsMemberOfType(convertedResult.Type, node.EnumeratorInfoOpt.GetEnumeratorInfo.Method); var enumeratorReturnType = GetReturnTypeWithState(reinferredGetEnumeratorMethod); if (enumeratorReturnType.State != NullableFlowState.NotNull) { if (!reportedDiagnostic && !(node.Expression is BoundConversion { Operand: { IsSuppressed: true } })) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, expr.Syntax.GetLocation()); } } var currentPropertyGetter = (MethodSymbol)AsMemberOfType(enumeratorReturnType.Type, node.EnumeratorInfoOpt.CurrentPropertyGetter); currentPropertyGetterTypeWithState = ApplyUnconditionalAnnotations( currentPropertyGetter.ReturnTypeWithAnnotations.ToTypeWithState(), currentPropertyGetter.ReturnTypeFlowAnalysisAnnotations); // Analyze `await MoveNextAsync()` if (node.AwaitOpt is { AwaitableInstancePlaceholder: BoundAwaitableValuePlaceholder moveNextPlaceholder } awaitMoveNextInfo) { var moveNextAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, node.EnumeratorInfoOpt.MoveNextInfo.Method); var result = new VisitResult(GetReturnTypeWithState(moveNextAsyncMethod), moveNextAsyncMethod.ReturnTypeWithAnnotations); AddPlaceholderReplacement(moveNextPlaceholder, moveNextPlaceholder, result); Visit(awaitMoveNextInfo); RemovePlaceholderReplacement(moveNextPlaceholder); } // Analyze `await DisposeAsync()` if (node.EnumeratorInfoOpt is { NeedsDisposal: true, DisposeAwaitableInfo: BoundAwaitableInfo awaitDisposalInfo }) { var disposalPlaceholder = awaitDisposalInfo.AwaitableInstancePlaceholder; bool addedPlaceholder = false; if (node.EnumeratorInfoOpt.PatternDisposeInfo is { Method: var originalDisposeMethod }) // no statically known Dispose method if doing a runtime check { Debug.Assert(disposalPlaceholder is not null); var disposeAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, originalDisposeMethod); var result = new VisitResult(GetReturnTypeWithState(disposeAsyncMethod), disposeAsyncMethod.ReturnTypeWithAnnotations); AddPlaceholderReplacement(disposalPlaceholder, disposalPlaceholder, result); addedPlaceholder = true; } Visit(awaitDisposalInfo); if (addedPlaceholder) { RemovePlaceholderReplacement(disposalPlaceholder!); } } } SetResultType(expression: null, currentPropertyGetterTypeWithState); } public override void VisitForEachIterationVariables(BoundForEachStatement node) { // ResultType should have been set by VisitForEachExpression, called just before this. var sourceState = node.EnumeratorInfoOpt == null ? default : ResultType; TypeWithAnnotations sourceType = sourceState.ToTypeWithAnnotations(compilation); #pragma warning disable IDE0055 // Fix formatting var variableLocation = node.Syntax switch { ForEachStatementSyntax statement => statement.Identifier.GetLocation(), ForEachVariableStatementSyntax variableStatement => variableStatement.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Syntax) }; #pragma warning restore IDE0055 // Fix formatting if (node.DeconstructionOpt is object) { var assignment = node.DeconstructionOpt.DeconstructionAssignment; // Visit the assignment as a deconstruction with an explicit type VisitDeconstructionAssignmentOperator(assignment, sourceState.HasNullType ? (TypeWithState?)null : sourceState); // https://github.com/dotnet/roslyn/issues/35010: if the iteration variable is a tuple deconstruction, we need to put something in the tree Visit(node.IterationVariableType); } else { Visit(node.IterationVariableType); foreach (var iterationVariable in node.IterationVariables) { var state = NullableFlowState.NotNull; if (!sourceState.HasNullType) { TypeWithAnnotations destinationType = iterationVariable.TypeWithAnnotations; TypeWithState result = sourceState; TypeWithState resultForType = sourceState; if (iterationVariable.IsRef) { // foreach (ref DestinationType variable in collection) if (IsNullabilityMismatch(sourceType, destinationType)) { var foreachSyntax = (ForEachStatementSyntax)node.Syntax; ReportNullabilityMismatchInAssignment(foreachSyntax.Type, sourceType, destinationType); } } else if (iterationVariable is SourceLocalSymbol { IsVar: true }) { // foreach (var variable in collection) destinationType = sourceState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(iterationVariable, destinationType); resultForType = destinationType.ToTypeWithState(); } else { // foreach (DestinationType variable in collection) // and asynchronous variants var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Conversion conversion = BoundNode.GetConversion(node.ElementConversion, node.ElementPlaceholder); if (conversion.Kind == ConversionKind.NoConversion) { conversion = _conversions.ClassifyImplicitConversionFromType(sourceType.Type, destinationType.Type, ref discardedUseSiteInfo); } result = VisitConversion( conversionOpt: null, conversionOperand: node.IterationVariableType, conversion, destinationType, sourceState, checkConversion: true, fromExplicitCast: !conversion.IsImplicit, useLegacyWarnings: true, AssignmentKind.ForEachIterationVariable, reportTopLevelWarnings: true, reportRemainingWarnings: true, diagnosticLocationOpt: variableLocation); } // In non-error cases we'll only run this loop a single time. In error cases we'll set the nullability of the VariableType multiple times, but at least end up with something SetAnalyzedNullability(node.IterationVariableType, new VisitResult(resultForType, destinationType), isLvalue: true); state = result.State; } int slot = GetOrCreateSlot(iterationVariable); if (slot > 0) { this.State[slot] = state; } } } } public override BoundNode? VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { var result = base.VisitFromEndIndexExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitObjectInitializerMember(BoundObjectInitializerMember node) { // Should be handled by VisitObjectCreationExpression. throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { SetNotNullResult(node); return null; } public override BoundNode? VisitBadExpression(BoundBadExpression node) { foreach (var child in node.ChildBoundNodes) { // https://github.com/dotnet/roslyn/issues/35042, we need to implement similar workarounds for object, collection, and dynamic initializers. if (child is BoundLambda lambda) { TakeIncrementalSnapshot(lambda); VisitLambda(lambda, delegateTypeOpt: null); VisitRvalueEpilogue(lambda); } else { VisitRvalue(child as BoundExpression); } } var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return null; } public override BoundNode? VisitTypeExpression(BoundTypeExpression node) { var result = base.VisitTypeExpression(node); if (node.BoundContainingTypeOpt != null) { VisitTypeExpression(node.BoundContainingTypeOpt); } SetNotNullResult(node); return result; } public override BoundNode? VisitTypeOrValueExpression(BoundTypeOrValueExpression node) { // These should not appear after initial binding except in error cases. var result = base.VisitTypeOrValueExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitUnaryOperator(BoundUnaryOperator node) { Debug.Assert(!IsConditionalState); TypeWithState resultType; switch (node.OperatorKind) { case UnaryOperatorKind.BoolLogicalNegation: Visit(node.Operand); if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicTrue: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicLogicalNegation: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); // If the state is split, the result is `bool` at runtime and we invert it here. if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; default: if (node.OperatorKind.IsUserDefined() && node.MethodOpt is MethodSymbol method && method.ParameterCount == 1) { var (operand, conversion) = RemoveConversion(node.Operand, includeExplicitConversions: false); VisitRvalue(operand); var operandResult = ResultType; bool isLifted = node.OperatorKind.IsLifted(); var operandType = GetNullableUnderlyingTypeIfNecessary(isLifted, operandResult); // Update method based on inferred operand type. method = (MethodSymbol)AsMemberOfType(operandType.Type!.StrippedType(), method); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameter = method.Parameters[0]; _ = VisitConversion( node.Operand as BoundConversion, operand, conversion, parameter.TypeWithAnnotations, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter); resultType = GetLiftedReturnTypeIfNecessary(isLifted, method.ReturnTypeWithAnnotations, operandResult.State); SetUpdatedSymbol(node, node.MethodOpt, method); } else { VisitRvalue(node.Operand); resultType = adjustForLifting(ResultType); } break; } SetResultType(node, resultType); return null; TypeWithState adjustForLifting(TypeWithState argumentResult) => TypeWithState.Create(node.Type, node.OperatorKind.IsLifted() ? argumentResult.State : NullableFlowState.NotNull); } public override BoundNode? VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { var result = base.VisitPointerIndirectionOperator(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitPointerElementAccess(BoundPointerElementAccess node) { var result = base.VisitPointerElementAccess(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitRefTypeOperator(BoundRefTypeOperator node) { VisitRvalue(node.Operand); SetNotNullResult(node); return null; } public override BoundNode? VisitMakeRefOperator(BoundMakeRefOperator node) { var result = base.VisitMakeRefOperator(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRefValueOperator(BoundRefValueOperator node) { var result = base.VisitRefValueOperator(node); var type = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetLvalueResultType(node, type); return result; } private TypeWithState InferResultNullability(BoundUserDefinedConditionalLogicalOperator node) { if (node.OperatorKind.IsLifted()) { // https://github.com/dotnet/roslyn/issues/33879 Conversions: Lifted operator // Should this use the updated flow type and state? How should it compute nullability? return TypeWithState.Create(node.Type, NullableFlowState.NotNull); } // Update method based on inferred operand types: see https://github.com/dotnet/roslyn/issues/29605. // Analyze operator result properly (honoring [Maybe|NotNull] and [Maybe|NotNullWhen] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if ((object)node.LogicalOperator != null && node.LogicalOperator.ParameterCount == 2) { return GetReturnTypeWithState(node.LogicalOperator); } else { return default; } } protected override void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression node, BoundExpression right, bool isAnd, bool isBool, ref LocalState leftTrue, ref LocalState leftFalse) { Debug.Assert(!IsConditionalState); TypeWithState leftType = ResultType; // https://github.com/dotnet/roslyn/issues/29605 Update operator methods based on inferred operand types. MethodSymbol? logicalOperator = null; MethodSymbol? trueFalseOperator = null; BoundExpression? left = null; switch (node.Kind) { case BoundKind.BinaryOperator: Debug.Assert(!((BoundBinaryOperator)node).OperatorKind.IsUserDefined()); break; case BoundKind.UserDefinedConditionalLogicalOperator: var binary = (BoundUserDefinedConditionalLogicalOperator)node; if (binary.LogicalOperator != null && binary.LogicalOperator.ParameterCount == 2) { logicalOperator = binary.LogicalOperator; left = binary.Left; trueFalseOperator = isAnd ? binary.FalseOperator : binary.TrueOperator; if ((object)trueFalseOperator != null && trueFalseOperator.ParameterCount != 1) { trueFalseOperator = null; } } break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } Debug.Assert(trueFalseOperator is null || logicalOperator is object); Debug.Assert(logicalOperator is null || left is object); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if (trueFalseOperator is object) { ReportArgumentWarnings(left!, leftType, trueFalseOperator.Parameters[0]); } if (logicalOperator is object) { ReportArgumentWarnings(left!, leftType, logicalOperator.Parameters[0]); } Visit(right); TypeWithState rightType = ResultType; SetResultType(node, InferResultNullabilityOfBinaryLogicalOperator(node, leftType, rightType)); if (logicalOperator is object) { ReportArgumentWarnings(right, rightType, logicalOperator.Parameters[1]); } AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(node, right, isAnd, isBool, ref leftTrue, ref leftFalse); } private TypeWithState InferResultNullabilityOfBinaryLogicalOperator(BoundExpression node, TypeWithState leftType, TypeWithState rightType) { return node switch { BoundBinaryOperator binary => InferResultNullability(binary.OperatorKind, binary.Method, binary.Type, leftType, rightType), BoundUserDefinedConditionalLogicalOperator userDefined => InferResultNullability(userDefined), _ => throw ExceptionUtilities.UnexpectedValue(node) }; } public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) { var result = base.VisitAwaitExpression(node); var awaitableInfo = node.AwaitableInfo; var placeholder = awaitableInfo.AwaitableInstancePlaceholder; Debug.Assert(placeholder is object); AddPlaceholderReplacement(placeholder, node.Expression, _visitResult); Visit(awaitableInfo); RemovePlaceholderReplacement(placeholder); if (node.Type.IsValueType || node.HasErrors || awaitableInfo.GetResult is null) { SetNotNullResult(node); } else { // It is possible for the awaiter type returned from GetAwaiter to not be a named type. e.g. it could be a type parameter. // Proper handling of this is additional work which only benefits a very uncommon scenario, // so we will just use the originally bound GetResult method in this case. var getResult = awaitableInfo.GetResult; var reinferredGetResult = _visitResult.RValueType.Type is NamedTypeSymbol taskAwaiterType ? getResult.OriginalDefinition.AsMember(taskAwaiterType) : getResult; SetResultType(node, reinferredGetResult.ReturnTypeWithAnnotations.ToTypeWithState()); } return result; } public override BoundNode? VisitTypeOfOperator(BoundTypeOfOperator node) { var result = base.VisitTypeOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitMethodInfo(BoundMethodInfo node) { var result = base.VisitMethodInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitFieldInfo(BoundFieldInfo node) { var result = base.VisitFieldInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) { // Can occur in error scenarios and lambda scenarios var result = base.VisitDefaultLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.MaybeDefault)); return result; } public override BoundNode? VisitDefaultExpression(BoundDefaultExpression node) { Debug.Assert(!this.IsConditionalState); var result = base.VisitDefaultExpression(node); TypeSymbol type = node.Type; if (EmptyStructTypeCache.IsTrackableStructType(type)) { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; InheritNullableStateOfTrackableStruct(type, slot, valueSlot: -1, isDefaultValue: true); } } // https://github.com/dotnet/roslyn/issues/33344: this fails to produce an updated tuple type for a default expression // (should produce nullable element types for those elements that are of reference types) SetResultType(node, TypeWithState.ForType(type)); return result; } public override BoundNode? VisitIsOperator(BoundIsOperator node) { Debug.Assert(!this.IsConditionalState); var operand = node.Operand; var typeExpr = node.TargetType; VisitPossibleConditionalAccess(operand, out var conditionalStateWhenNotNull); Unsplit(); LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } Debug.Assert(node.Type.SpecialType == SpecialType.System_Boolean); SetConditionalState(stateWhenNotNull, State); if (typeExpr.Type?.SpecialType == SpecialType.System_Object) { LearnFromNullTest(operand, ref StateWhenFalse); } VisitTypeExpression(typeExpr); SetNotNullResult(node); return null; } public override BoundNode? VisitAsOperator(BoundAsOperator node) { var argumentType = VisitRvalueWithState(node.Operand); NullableFlowState resultState = NullableFlowState.NotNull; var type = node.Type; if (type.CanContainNull()) { switch (BoundNode.GetConversion(node.OperandConversion, node.OperandPlaceholder).Kind) { case ConversionKind.Identity: case ConversionKind.ImplicitReference: case ConversionKind.Boxing: case ConversionKind.ImplicitNullable: resultState = argumentType.State; break; default: resultState = NullableFlowState.MaybeDefault; break; } } VisitTypeExpression(node.TargetType); SetResultType(node, TypeWithState.Create(type, resultState)); return null; } public override BoundNode? VisitSizeOfOperator(BoundSizeOfOperator node) { var result = base.VisitSizeOfOperator(node); VisitTypeExpression(node.SourceType); SetNotNullResult(node); return result; } public override BoundNode? VisitArgList(BoundArgList node) { var result = base.VisitArgList(node); Debug.Assert(node.Type.SpecialType == SpecialType.System_RuntimeArgumentHandle); SetNotNullResult(node); return result; } public override BoundNode? VisitArgListOperator(BoundArgListOperator node) { VisitArgumentsEvaluate(node.Arguments, node.ArgumentRefKindsOpt, parameterAnnotationsOpt: default, defaultArguments: default); Debug.Assert(node.Type is null); SetNotNullResult(node); return null; } public override BoundNode? VisitLiteral(BoundLiteral node) { Debug.Assert(!IsConditionalState); var result = base.VisitLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, node.Type?.CanContainNull() != false && node.ConstantValue?.IsNull == true ? NullableFlowState.MaybeDefault : NullableFlowState.NotNull)); return result; } public override BoundNode? VisitUtf8String(BoundUtf8String node) { Debug.Assert(!IsConditionalState); var result = base.VisitUtf8String(node); SetNotNullResult(node); return result; } public override BoundNode? VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { var result = base.VisitPreviousSubmissionReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitHostObjectMemberReference(BoundHostObjectMemberReference node) { var result = base.VisitHostObjectMemberReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitPseudoVariable(BoundPseudoVariable node) { var result = base.VisitPseudoVariable(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeExpression(BoundRangeExpression node) { var result = base.VisitRangeExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeVariable(BoundRangeVariable node) { VisitWithoutDiagnostics(node.Value); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Need to review this return null; } public override BoundNode? VisitLabel(BoundLabel node) { var result = base.VisitLabel(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitDynamicInvocation(BoundDynamicInvocation node) { var expr = node.Expression; VisitRvalue(expr); // If the expression was a MethodGroup, check nullability of receiver. var receiverOpt = (expr as BoundMethodGroup)?.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } VisitArgumentsEvaluate(node.Arguments, node.ArgumentRefKindsOpt, parameterAnnotationsOpt: default, defaultArguments: default); Debug.Assert(node.Type.IsDynamic()); Debug.Assert(node.Type.IsReferenceType); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { var receiverOpt = node.ReceiverOpt; VisitRvalue(receiverOpt); Debug.Assert(!IsConditionalState); var @event = node.Event; if ([email protected]) { @event = (EventSymbol)AsMemberOfType(ResultType.Type, @event); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); SetUpdatedSymbol(node, node.Event, @event); } VisitRvalue(node.Argument); // https://github.com/dotnet/roslyn/issues/31018: Check for delegate mismatch. if (node.Argument.ConstantValue?.IsNull != true && MakeMemberSlot(receiverOpt, @event) is > 0 and var memberSlot) { this.State[memberSlot] = node.IsAddition ? this.State[memberSlot].Meet(ResultType.State) : NullableFlowState.MaybeNull; } SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29969 Review whether this is the correct result return null; } public override BoundNode? VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { VisitObjectCreationExpressionBase(node); return null; } public override BoundNode? VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitImplicitReceiver(BoundImplicitReceiver node) { var result = base.VisitImplicitReceiver(node); SetNotNullResult(node); return result; } public override BoundNode? VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node) { throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) { VisitObjectCreationExpressionBase(node); return null; } public override BoundNode? VisitNewT(BoundNewT node) { VisitObjectCreationExpressionBase(node); return null; } public override BoundNode? VisitArrayInitialization(BoundArrayInitialization node) { var result = base.VisitArrayInitialization(node); SetNotNullResult(node); return result; } private void SetUnknownResultNullability(BoundExpression expression) { SetResultType(expression, TypeWithState.Create(expression.Type, default)); } public override BoundNode? VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); VisitArgumentsEvaluate(node.Arguments, node.ArgumentRefKindsOpt, parameterAnnotationsOpt: default, defaultArguments: default); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, bool checkNullableValueType = false) { return CheckPossibleNullReceiver(receiverOpt, ResultType, checkNullableValueType); } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, TypeWithState resultType, bool checkNullableValueType) { Debug.Assert(!this.IsConditionalState); bool reportedDiagnostic = false; if (receiverOpt != null && this.State.Reachable) { var resultTypeSymbol = resultType.Type; if (resultTypeSymbol is null) { return false; } #if DEBUG Debug.Assert(receiverOpt.Type is null || AreCloseEnough(receiverOpt.Type, resultTypeSymbol)); #endif if (!ReportPossibleNullReceiverIfNeeded(resultTypeSymbol, resultType.State, checkNullableValueType, receiverOpt.Syntax, out reportedDiagnostic)) { return reportedDiagnostic; } LearnFromNonNullTest(receiverOpt, ref this.State); } return reportedDiagnostic; } // Returns false if the type wasn't interesting private bool ReportPossibleNullReceiverIfNeeded(TypeSymbol type, NullableFlowState state, bool checkNullableValueType, SyntaxNode syntax, out bool reportedDiagnostic) { reportedDiagnostic = false; if (state.MayBeNull()) { bool isValueType = type.IsValueType; if (isValueType && (!checkNullableValueType || !type.IsNullableTypeOrTypeParameter() || type.GetNullableUnderlyingType().IsErrorType())) { return false; } ReportDiagnostic(isValueType ? ErrorCode.WRN_NullableValueTypeMayBeNull : ErrorCode.WRN_NullReferenceReceiver, syntax); reportedDiagnostic = true; } return true; } private void CheckExtensionMethodThisNullability(BoundExpression expr, Conversion conversion, ParameterSymbol parameter, TypeWithState result) { VisitArgumentConversionAndInboundAssignmentsAndPreConditions( conversionOpt: null, expr, conversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(result, result.ToTypeWithAnnotations(compilation)), stateForLambda: default), conversionResultsBuilder: null, extensionMethodThisArgument: true); } private static bool IsNullabilityMismatch(TypeWithAnnotations type1, TypeWithAnnotations type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } private static bool IsNullabilityMismatch(TypeSymbol type1, TypeSymbol type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } public override BoundNode? VisitQueryClause(BoundQueryClause node) { var result = base.VisitQueryClause(node); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Implement nullability analysis in LINQ queries return result; } public override BoundNode? VisitNameOfOperator(BoundNameOfOperator node) { var result = base.VisitNameOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNamespaceExpression(BoundNamespaceExpression node) { var result = base.VisitNamespaceExpression(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) { // This is only involved with unbound lambdas or when visiting the source of a converted tuple literal var result = base.VisitUnconvertedInterpolatedString(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitStringInsert(BoundStringInsert node) { var result = base.VisitStringInsert(node); SetUnknownResultNullability(node); return result; } protected override void VisitInterpolatedStringHandlerConstructor(BoundExpression? constructor) { // We skip visiting the constructor at this stage. We will visit it manually when VisitConversion is // called on the interpolated string handler } public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { // These placeholders don't yet follow proper placeholder discipline AssertPlaceholderAllowedWithoutRegistration(node); SetNotNullResult(node); return null; } public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { VisitPlaceholderWithReplacement(node); return null; } public override BoundNode? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { Debug.Assert(node.Type is null || node.Type.IsErrorType() || node.Type.IsRefLikeType); return VisitStackAllocArrayCreationBase(node); } public override BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { return VisitStackAllocArrayCreationBase(node); } private BoundNode? VisitStackAllocArrayCreationBase(BoundStackAllocArrayCreationBase node) { VisitRvalue(node.Count); var initialization = node.InitializerOpt; if (initialization is null) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return null; } Debug.Assert(node.Type is not null); var type = VisitArrayInitialization(node.Type, initialization, node.HasErrors); SetResultType(node, TypeWithState.Create(type, NullableFlowState.NotNull)); return null; } public override BoundNode? VisitDiscardExpression(BoundDiscardExpression node) { var result = TypeWithAnnotations.Create(node.Type); var rValueType = TypeWithState.ForType(node.Type); SetResult(node, rValueType, result); return null; } public override BoundNode? VisitThrowExpression(BoundThrowExpression node) { VisitThrow(node.Expression); SetResultType(node, default); return null; } public override BoundNode? VisitThrowStatement(BoundThrowStatement node) { VisitThrow(node.ExpressionOpt); return null; } private void VisitThrow(BoundExpression? expr) { if (expr != null) { var result = VisitRvalueWithState(expr); // Cases: // null // null! // Other (typed) expression, including suppressed ones if (result.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_ThrowPossibleNull, expr.Syntax); } } SetUnreachable(); } public override BoundNode? VisitYieldReturnStatement(BoundYieldReturnStatement node) { BoundExpression expr = node.Expression; if (expr == null) { return null; } var method = (MethodSymbol)CurrentSymbol; TypeWithAnnotations elementType = InMethodBinder.GetIteratorElementTypeFromReturnType(compilation, RefKind.None, method.ReturnType, errorLocation: null, diagnostics: null); _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); Unsplit(); return null; } protected override void VisitCatchBlock(BoundCatchBlock node, ref LocalState finallyState) { TakeIncrementalSnapshot(node); if (node.Locals.Length > 0) { LocalSymbol local = node.Locals[0]; if (local.DeclarationKind == LocalDeclarationKind.CatchVariable) { int slot = GetOrCreateSlot(local); if (slot > 0) this.State[slot] = NullableFlowState.NotNull; } } if (node.ExceptionSourceOpt != null) { VisitWithoutDiagnostics(node.ExceptionSourceOpt); } base.VisitCatchBlock(node, ref finallyState); } public override BoundNode? VisitLockStatement(BoundLockStatement node) { VisitRvalue(node.Argument); _ = CheckPossibleNullReceiver(node.Argument); VisitStatement(node.Body); return null; } public override BoundNode? VisitAttribute(BoundAttribute node) { VisitArguments(node, node.ConstructorArguments, ImmutableArray<RefKind>.Empty, node.Constructor, argsToParamsOpt: node.ConstructorArgumentsToParamsOpt, defaultArguments: default, expanded: node.ConstructorExpanded, invokedAsExtensionMethod: false); foreach (var assignment in node.NamedArguments) { Visit(assignment); } SetNotNullResult(node); return null; } public override BoundNode? VisitExpressionWithNullability(BoundExpressionWithNullability node) { var typeWithAnnotations = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetResult(node.Expression, typeWithAnnotations.ToTypeWithState(), typeWithAnnotations); return null; } public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { // These placeholders don't yet follow proper placeholder discipline AssertPlaceholderAllowedWithoutRegistration(node); SetNotNullResult(node); return null; } public override BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { // These placeholders don't yet follow proper placeholder discipline AssertPlaceholderAllowedWithoutRegistration(node); SetNotNullResult(node); return null; } public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { // These placeholders don't always follow proper placeholder discipline yet AssertPlaceholderAllowedWithoutRegistration(node); VisitPlaceholderWithReplacement(node); return null; } private void VisitPlaceholderWithReplacement(BoundValuePlaceholderBase node) { if (_resultForPlaceholdersOpt != null && _resultForPlaceholdersOpt.TryGetValue(node, out var value)) { var result = value.Result; SetResult(node, result.RValueType, result.LValueType); } else { AssertPlaceholderAllowedWithoutRegistration(node); SetNotNullResult(node); } } public override BoundNode? VisitAwaitableInfo(BoundAwaitableInfo node) { Visit(node.AwaitableInstancePlaceholder); Visit(node.GetAwaiter); return null; } public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) { _ = Visit(node.InvokedExpression); Debug.Assert(ResultType is TypeWithState { Type: FunctionPointerTypeSymbol { }, State: NullableFlowState.NotNull }); _ = VisitArguments( node, node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature, argsToParamsOpt: default, defaultArguments: default, expanded: false, invokedAsExtensionMethod: false); var returnTypeWithAnnotations = node.FunctionPointer.Signature.ReturnTypeWithAnnotations; SetResult(node, returnTypeWithAnnotations.ToTypeWithState(), returnTypeWithAnnotations); return null; } protected override string Dump(LocalState state) { return state.Dump(_variables); } protected override bool Meet(ref LocalState self, ref LocalState other) { if (!self.Reachable) return false; if (!other.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Meet(in other); } protected override bool Join(ref LocalState self, ref LocalState other) { if (!other.Reachable) return false; if (!self.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Join(in other); } private void Join(ref PossiblyConditionalState other) { var otherIsConditional = other.IsConditionalState; if (otherIsConditional) { Split(); } if (IsConditionalState) { Join(ref StateWhenTrue, ref otherIsConditional ? ref other.StateWhenTrue : ref other.State); Join(ref StateWhenFalse, ref otherIsConditional ? ref other.StateWhenFalse : ref other.State); } else { Debug.Assert(!otherIsConditional); Join(ref State, ref other.State); } } private LocalState CloneAndUnsplit(ref PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { return conditionalState.State.Clone(); } var state = conditionalState.StateWhenTrue.Clone(); Join(ref state, ref conditionalState.StateWhenFalse); return state; } private void SetPossiblyConditionalState(in PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { SetState(conditionalState.State); } else { SetConditionalState(conditionalState.StateWhenTrue, conditionalState.StateWhenFalse); } } internal sealed class LocalStateSnapshot { internal readonly int Id; internal readonly LocalStateSnapshot? Container; internal readonly BitVector State; internal LocalStateSnapshot(int id, LocalStateSnapshot? container, BitVector state) { Id = id; Container = container; State = state; } } /// <summary> /// A bit array containing the nullability of variables associated with a method scope. If the method is a /// nested function (a lambda or a local function), there is a reference to the corresponding instance for /// the containing method scope. The instances in the chain are associated with a corresponding /// <see cref="Variables"/> chain, and the <see cref="Id"/> field in this type matches <see cref="Variables.Id"/>. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct LocalState : ILocalDataFlowState { private sealed class Boxed { internal LocalState Value; internal Boxed(LocalState value) { Value = value; } } internal readonly int Id; private readonly Boxed? _container; // The representation of a state is a bit vector with two bits per slot: // (false, false) => NotNull, (false, true) => MaybeNull, (true, true) => MaybeDefault. // Slot 0 is used to represent whether the state is reachable (true) or not. private BitVector _state; private LocalState(int id, Boxed? container, BitVector state) { Id = id; _container = container; _state = state; } internal static LocalState Create(LocalStateSnapshot snapshot) { var container = snapshot.Container is null ? null : new Boxed(Create(snapshot.Container)); return new LocalState(snapshot.Id, container, snapshot.State.Clone()); } internal LocalStateSnapshot CreateSnapshot() { return new LocalStateSnapshot(Id, _container?.Value.CreateSnapshot(), _state.Clone()); } public bool Reachable => _state[0]; public bool NormalizeToBottom => false; public static LocalState ReachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: true); } public static LocalState UnreachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: false); } private static LocalState CreateReachableOrUnreachableState(Variables variables, bool reachable) { var container = variables.Container is null ? null : new Boxed(CreateReachableOrUnreachableState(variables.Container, reachable)); int capacity = reachable ? variables.NextAvailableIndex : 1; return new LocalState(variables.Id, container, CreateBitVector(capacity, reachable)); } public LocalState CreateNestedMethodState(Variables variables) { Debug.Assert(Id == variables.Container!.Id); return new LocalState(variables.Id, container: new Boxed(this), CreateBitVector(capacity: variables.NextAvailableIndex, reachable: true)); } private static BitVector CreateBitVector(int capacity, bool reachable) { if (capacity < 1) capacity = 1; BitVector state = BitVector.Create(capacity * 2); state[0] = reachable; return state; } private int Capacity => _state.Capacity / 2; private void EnsureCapacity(int capacity) { _state.EnsureCapacity(capacity * 2); } public bool HasVariable(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasVariable(id, index); } private bool HasVariable(int id, int index) { if (Id > id) { return _container!.Value.HasValue(id, index); } else { return Id == id; } } public bool HasValue(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasValue(id, index); } private bool HasValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.HasValue(id, index); } else { return index < Capacity; } } public void Normalize(NullableWalker walker, Variables variables) { if (Id != variables.Id) { Debug.Assert(Id < variables.Id); Normalize(walker, variables.Container!); } else { _container?.Value.Normalize(walker, variables.Container!); int start = Capacity; EnsureCapacity(variables.NextAvailableIndex); Populate(walker, start); } } public void PopulateAll(NullableWalker walker) { _container?.Value.PopulateAll(walker); Populate(walker, start: 1); } private void Populate(NullableWalker walker, int start) { int capacity = Capacity; for (int index = start; index < capacity; index++) { int slot = Variables.ConstructSlot(Id, index); SetValue(Id, index, walker.GetDefaultState(ref this, slot)); } } public NullableFlowState this[int slot] { get { (int id, int index) = Variables.DeconstructSlot(slot); return GetValue(id, index); } set { (int id, int index) = Variables.DeconstructSlot(slot); SetValue(id, index, value); } } private NullableFlowState GetValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.GetValue(id, index); } else { if (index < Capacity && this.Reachable) { index *= 2; var result = (_state[index + 1], _state[index]) switch { (false, false) => NullableFlowState.NotNull, (false, true) => NullableFlowState.MaybeNull, (true, false) => throw ExceptionUtilities.UnexpectedValue(index), (true, true) => NullableFlowState.MaybeDefault }; return result; } return NullableFlowState.NotNull; } } private void SetValue(int id, int index, NullableFlowState value) { if (Id != id) { Debug.Assert(Id > id); _container!.Value.SetValue(id, index, value); } else { // No states should be modified in unreachable code, as there is only one unreachable state. if (!this.Reachable) return; index *= 2; _state[index] = (value != NullableFlowState.NotNull); _state[index + 1] = (value == NullableFlowState.MaybeDefault); } } internal void ForEach<TArg>(Action<int, TArg> action, TArg arg) { _container?.Value.ForEach(action, arg); for (int index = 1; index < Capacity; index++) { action(Variables.ConstructSlot(Id, index), arg); } } internal LocalState GetStateForVariables(int id) { var state = this; while (state.Id != id) { state = state._container!.Value; } return state; } /// <summary> /// Produce a duplicate of this flow analysis state. /// </summary> /// <returns></returns> public LocalState Clone() { var container = _container is null ? null : new Boxed(_container.Value.Clone()); return new LocalState(Id, container, _state.Clone()); } public bool Join(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Join(in other._container!.Value)) { result = true; } if (_state.UnionWith(in other._state)) { result = true; } return result; } public bool Meet(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Meet(in other._container!.Value)) { result = true; } if (_state.IntersectWith(in other._state)) { result = true; } return result; } internal string GetDebuggerDisplay() { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(" "); int n = Math.Min(Capacity, 8); for (int i = n - 1; i >= 0; i--) builder.Append(_state[i * 2] ? '?' : '!'); return pooledBuilder.ToStringAndFree(); } internal string Dump(Variables variables) { if (!this.Reachable) return "unreachable"; if (Id != variables.Id) return "invalid"; var builder = PooledStringBuilder.GetInstance(); Dump(builder, variables); return builder.ToStringAndFree(); } private void Dump(StringBuilder builder, Variables variables) { _container?.Value.Dump(builder, variables.Container!); for (int index = 1; index < Capacity; index++) { if (getName(Variables.ConstructSlot(Id, index)) is string name) { builder.Append(name); var annotation = GetValue(Id, index) switch { NullableFlowState.MaybeNull => "?", NullableFlowState.MaybeDefault => "??", _ => "!" }; builder.Append(annotation); } } string? getName(int slot) { VariableIdentifier id = variables[slot]; var name = id.Symbol.Name; int containingSlot = id.ContainingSlot; return containingSlot > 0 ? getName(containingSlot) + "." + name : name; } } } internal sealed class LocalFunctionState : AbstractLocalFunctionState { /// <summary> /// Defines the starting state used in the local function body to /// produce diagnostics and determine types. /// </summary> public LocalState StartingState; public LocalFunctionState(LocalState unreachableState) : base(unreachableState.Clone(), unreachableState.Clone()) { StartingState = unreachableState; } } protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol) { var variables = (symbol.ContainingSymbol is MethodSymbol containingMethod ? _variables.GetVariablesForMethodScope(containingMethod) : null) ?? _variables.GetRootScope(); return new LocalFunctionState(LocalState.UnreachableState(variables)); } private sealed class NullabilityInfoTypeComparer : IEqualityComparer<(NullabilityInfo info, TypeSymbol? type)> { public static readonly NullabilityInfoTypeComparer Instance = new NullabilityInfoTypeComparer(); public bool Equals((NullabilityInfo info, TypeSymbol? type) x, (NullabilityInfo info, TypeSymbol? type) y) { return x.info.Equals(y.info) && Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(x.type, y.type); } public int GetHashCode((NullabilityInfo info, TypeSymbol? type) obj) { return obj.GetHashCode(); } } private sealed class ExpressionAndSymbolEqualityComparer : IEqualityComparer<(BoundNode? expr, Symbol symbol)> { internal static readonly ExpressionAndSymbolEqualityComparer Instance = new ExpressionAndSymbolEqualityComparer(); private ExpressionAndSymbolEqualityComparer() { } public bool Equals((BoundNode? expr, Symbol symbol) x, (BoundNode? expr, Symbol symbol) y) { RoslynDebug.Assert(x.symbol is object); RoslynDebug.Assert(y.symbol is object); // We specifically use reference equality for the symbols here because the BoundNode should be immutable. // We should be storing and retrieving the exact same instance of the symbol, not just an "equivalent" // symbol. return x.expr == y.expr && (object)x.symbol == y.symbol; } public int GetHashCode((BoundNode? expr, Symbol symbol) obj) { RoslynDebug.Assert(obj.symbol is object); return Hash.Combine(obj.expr, obj.symbol.GetHashCode()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Nullability flow analysis. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed partial class NullableWalker : LocalDataFlowPass<NullableWalker.LocalState, NullableWalker.LocalFunctionState> { /// <summary> /// Nullable analysis data for methods, parameter default values, and attributes /// stored on the Compilation during testing only. /// The key is a symbol for methods or parameters, and syntax for attributes. /// </summary> internal sealed class NullableAnalysisData { internal readonly int MaxRecursionDepth; internal readonly ConcurrentDictionary<object, NullableWalker.Data> Data; internal NullableAnalysisData(int maxRecursionDepth = -1) { MaxRecursionDepth = maxRecursionDepth; Data = new ConcurrentDictionary<object, NullableWalker.Data>(); } } /// <summary> /// Used to copy variable slots and types from the NullableWalker for the containing method /// or lambda to the NullableWalker created for a nested lambda or local function. /// </summary> internal sealed class VariableState { // Consider referencing the Variables instance directly from the original NullableWalker // rather than cloning. (Items are added to the collections but never replaced so the // collections are lazily populated but otherwise immutable. We'd probably want a // clone when analyzing from speculative semantic model though.) internal readonly VariablesSnapshot Variables; // The nullable state of all variables captured at the point where the function or lambda appeared. internal readonly LocalStateSnapshot VariableNullableStates; internal VariableState(VariablesSnapshot variables, LocalStateSnapshot variableNullableStates) { Variables = variables; VariableNullableStates = variableNullableStates; } } /// <summary> /// Data recorded for a particular analysis run. /// </summary> internal readonly struct Data { /// <summary> /// Number of entries tracked during analysis. /// </summary> internal readonly int TrackedEntries; /// <summary> /// True if analysis was required; false if analysis was optional and results dropped. /// </summary> internal readonly bool RequiredAnalysis; internal Data(int trackedEntries, bool requiredAnalysis) { TrackedEntries = trackedEntries; RequiredAnalysis = requiredAnalysis; } } /// <summary> /// Represents the result of visiting an expression. /// Contains a result type which tells us whether the expression may be null, /// and an l-value type which tells us whether we can assign null to the expression. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] private readonly struct VisitResult { public readonly TypeWithState RValueType; public readonly TypeWithAnnotations LValueType; public VisitResult(TypeWithState rValueType, TypeWithAnnotations lValueType) { RValueType = rValueType; LValueType = lValueType; // https://github.com/dotnet/roslyn/issues/34993: Doesn't hold true for Tuple_Assignment_10. See if we can make it hold true //Debug.Assert((RValueType.Type is null && LValueType.TypeSymbol is null) || // RValueType.Type.Equals(LValueType.TypeSymbol, TypeCompareKind.ConsiderEverything | TypeCompareKind.AllIgnoreOptions)); } public VisitResult(TypeSymbol? type, NullableAnnotation annotation, NullableFlowState state) { RValueType = TypeWithState.Create(type, state); LValueType = TypeWithAnnotations.Create(type, annotation); Debug.Assert(TypeSymbol.Equals(RValueType.Type, LValueType.Type, TypeCompareKind.ConsiderEverything)); } internal string GetDebuggerDisplay() => $"{{LValue: {LValueType.GetDebuggerDisplay()}, RValue: {RValueType.GetDebuggerDisplay()}}}"; } /// <summary> /// Represents the result of visiting an argument expression. /// In addition to storing the <see cref="VisitResult"/>, also stores the <see cref="LocalState"/> /// for reanalyzing a lambda. /// </summary> [DebuggerDisplay("{VisitResult.GetDebuggerDisplay(), nq}")] private readonly struct VisitArgumentResult { public readonly VisitResult VisitResult; public readonly Optional<LocalState> StateForLambda; public TypeWithState RValueType => VisitResult.RValueType; public TypeWithAnnotations LValueType => VisitResult.LValueType; public VisitArgumentResult(VisitResult visitResult, Optional<LocalState> stateForLambda) { VisitResult = visitResult; StateForLambda = stateForLambda; } } private Variables _variables; /// <summary> /// Binder for symbol being analyzed. /// </summary> private readonly Binder _binder; /// <summary> /// Conversions with nullability and unknown matching any. /// </summary> private readonly Conversions _conversions; /// <summary> /// 'true' if non-nullable member warnings should be issued at return points. /// One situation where this is 'false' is when we are analyzing field initializers and there is a constructor symbol in the type. /// </summary> private readonly bool _useConstructorExitWarnings; /// <summary> /// If true, the parameter types and nullability from _delegateInvokeMethod is used for /// initial parameter state. If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeParameterTypes; /// <summary> /// If true, the return type and nullability from _delegateInvokeMethod is used. /// If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeReturnType; /// <summary> /// Method signature used for return or parameter types. Distinct from CurrentSymbol signature /// when CurrentSymbol is a lambda and type is inferred from MethodTypeInferrer. /// </summary> private MethodSymbol? _delegateInvokeMethod; /// <summary> /// Return statements and the result types from analyzing the returned expressions. Used when inferring lambda return type in MethodTypeInferrer. /// </summary> private ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? _returnTypesOpt; /// <summary> /// Invalid type, used only to catch Visit methods that do not set /// _result.Type. See VisitExpressionWithoutStackGuard. /// </summary> private static readonly TypeWithState _invalidType = TypeWithState.Create(ErrorTypeSymbol.UnknownResultType, NullableFlowState.NotNull); /// <summary> /// Contains the map of expressions to inferred nullabilities and types used by the optional rewriter phase of the /// compiler. /// </summary> private readonly ImmutableDictionary<BoundExpression, (NullabilityInfo Info, TypeSymbol? Type)>.Builder? _analyzedNullabilityMapOpt; /// <summary> /// Manages creating snapshots of the walker as appropriate. Null if we're not taking snapshots of /// this walker. /// </summary> private readonly SnapshotManager.Builder? _snapshotBuilderOpt; // https://github.com/dotnet/roslyn/issues/35043: remove this when all expression are supported private bool _disableNullabilityAnalysis; /// <summary> /// State of method group receivers, used later when analyzing the conversion to a delegate. /// (Could be replaced by _analyzedNullabilityMapOpt if that map is always available.) /// </summary> private PooledDictionary<BoundExpression, TypeWithState>? _methodGroupReceiverMapOpt; private PooledDictionary<BoundValuePlaceholderBase, (BoundExpression? Replacement, VisitResult Result)>? _resultForPlaceholdersOpt; /// <summary> /// Variables instances for each lambda or local function defined within the analyzed region. /// </summary> private PooledDictionary<MethodSymbol, Variables>? _nestedFunctionVariables; #if DEBUG private bool _completingTargetTypedExpression; #endif private PooledDictionary<BoundExpression, Func<TypeWithAnnotations, TypeWithState>>? _targetTypedAnalysisCompletionOpt; /// <summary> /// Map from a target-typed expression (such as a target-typed conditional, switch or new) to the delegate /// that completes analysis once the target type is known. /// The delegate is invoked by <see cref="VisitConversion(BoundConversion, BoundExpression, Conversion, TypeWithAnnotations, TypeWithState, bool, bool, bool, AssignmentKind, ParameterSymbol, bool, bool, bool, Optional&lt;LocalState&gt;,bool, Location, ArrayBuilder&lt;VisitResult&gt;)"/>. /// </summary> private PooledDictionary<BoundExpression, Func<TypeWithAnnotations, TypeWithState>> TargetTypedAnalysisCompletion => _targetTypedAnalysisCompletionOpt ??= PooledDictionary<BoundExpression, Func<TypeWithAnnotations, TypeWithState>>.GetInstance(); /// <summary> /// True if we're analyzing speculative code. This turns off some initialization steps /// that would otherwise be taken. /// </summary> private readonly bool _isSpeculative; /// <summary> /// True if this walker was created using an initial state. /// </summary> private readonly bool _hasInitialState; private readonly MethodSymbol? _baseOrThisInitializer; #if DEBUG /// <summary> /// Contains the expressions that should not be inserted into <see cref="_analyzedNullabilityMapOpt"/>. /// </summary> private static readonly ImmutableArray<BoundKind> s_skippedExpressions = ImmutableArray.Create(BoundKind.ArrayInitialization, BoundKind.ObjectInitializerExpression, BoundKind.CollectionInitializerExpression, BoundKind.DynamicCollectionElementInitializer); #endif /// <summary> /// The result and l-value type of the last visited expression. /// </summary> private VisitResult _visitResult; /// <summary> /// The visit result of the receiver for the current conditional access. /// /// For example: A conditional invocation uses a placeholder as a receiver. By storing the /// visit result from the actual receiver ahead of time, we can give this placeholder a correct result. /// </summary> private VisitResult _currentConditionalReceiverVisitResult; /// <summary> /// The result type represents the state of the last visited expression. /// </summary> private TypeWithState ResultType { get => _visitResult.RValueType; } private void SetResultType(BoundExpression? expression, TypeWithState type, bool updateAnalyzedNullability = true) { SetResult(expression, resultType: type, lvalueType: type.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: updateAnalyzedNullability); } private void SetAnalyzedNullability(BoundExpression? expression, TypeWithState type) { SetAnalyzedNullability(expression, resultType: type, lvalueType: type.ToTypeWithAnnotations(compilation)); } /// <summary> /// Force the inference of the LValueResultType from ResultType. /// </summary> private void UseRvalueOnly(BoundExpression? expression) { SetResult(expression, ResultType, ResultType.ToTypeWithAnnotations(compilation), isLvalue: false); } private TypeWithAnnotations LvalueResultType { get => _visitResult.LValueType; } private void SetLvalueResultType(BoundExpression? expression, TypeWithAnnotations type) { SetResult(expression, resultType: type.ToTypeWithState(), lvalueType: type); } /// <summary> /// Force the inference of the ResultType from LValueResultType. /// </summary> private void UseLvalueOnly(BoundExpression? expression) { SetResult(expression, LvalueResultType.ToTypeWithState(), LvalueResultType, isLvalue: true); } private void SetInvalidResult() => SetResult(expression: null, _invalidType, _invalidType.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: false); private void SetResult(BoundExpression? expression, TypeWithState resultType, TypeWithAnnotations lvalueType, bool updateAnalyzedNullability = true, bool? isLvalue = null) { _visitResult = new VisitResult(resultType, lvalueType); if (updateAnalyzedNullability) { SetAnalyzedNullability(expression, _visitResult, isLvalue); } } private void SetAnalyzedNullability(BoundExpression? expression, TypeWithState resultType, TypeWithAnnotations lvalueType, bool? isLvalue = null) { SetAnalyzedNullability(expression, new VisitResult(resultType, lvalueType), isLvalue); } private bool ShouldMakeNotNullRvalue(BoundExpression node) => node.IsSuppressed || node.HasAnyErrors || !IsReachable(); /// <summary> /// Sets the analyzed nullability of the expression to be the given result. /// </summary> private void SetAnalyzedNullability(BoundExpression? expr, VisitResult result, bool? isLvalue = null) { if (expr == null || _disableNullabilityAnalysis) return; #if DEBUG // https://github.com/dotnet/roslyn/issues/34993: This assert is essential for ensuring that we aren't // changing the observable results of GetTypeInfo beyond nullability information. //Debug.Assert(AreCloseEnough(expr.Type, result.RValueType.Type), // $"Cannot change the type of {expr} from {expr.Type} to {result.RValueType.Type}"); #endif if (_analyzedNullabilityMapOpt != null) { // https://github.com/dotnet/roslyn/issues/34993: enable and verify these assertions #if false if (_analyzedNullabilityMapOpt.TryGetValue(expr, out var existing)) { if (!(result.RValueType.State == NullableFlowState.NotNull && ShouldMakeNotNullRvalue(expr, State.Reachable))) { switch (isLvalue) { case true: Debug.Assert(existing.Info.Annotation == result.LValueType.NullableAnnotation.ToPublicAnnotation(), $"Tried to update the nullability of {expr} from {existing.Info.Annotation} to {result.LValueType.NullableAnnotation}"); break; case false: Debug.Assert(existing.Info.FlowState == result.RValueType.State, $"Tried to update the nullability of {expr} from {existing.Info.FlowState} to {result.RValueType.State}"); break; case null: Debug.Assert(existing.Info.Equals((NullabilityInfo)result), $"Tried to update the nullability of {expr} from ({existing.Info.Annotation}, {existing.Info.FlowState}) to ({result.LValueType.NullableAnnotation}, {result.RValueType.State})"); break; } } } #endif _analyzedNullabilityMapOpt[expr] = (new NullabilityInfo(result.LValueType.ToPublicAnnotation(), result.RValueType.State.ToPublicFlowState()), // https://github.com/dotnet/roslyn/issues/35046 We're dropping the result if the type doesn't match up completely // with the existing type expr.Type?.Equals(result.RValueType.Type, TypeCompareKind.AllIgnoreOptions) == true ? result.RValueType.Type : expr.Type); } } /// <summary> /// Placeholder locals, e.g. for objects being constructed. /// </summary> private PooledDictionary<object, PlaceholderLocal>? _placeholderLocalsOpt; /// <summary> /// For methods with annotations, we'll need to visit the arguments twice. /// Once for diagnostics and once for result state (but disabling diagnostics). /// </summary> private bool _disableDiagnostics = false; /// <summary> /// Whether we are going to read the currently visited expression. /// </summary> private bool _expressionIsRead = true; /// <summary> /// Used to allow <see cref="MakeSlot(BoundExpression)"/> to substitute the correct slot for a <see cref="BoundConditionalReceiver"/> when /// it's encountered. /// </summary> private int _lastConditionalAccessSlot = -1; private bool IsAnalyzingAttribute => methodMainNode.Kind == BoundKind.Attribute; protected override void Free() { AssertNoPlaceholderReplacements(); _nestedFunctionVariables?.Free(); _resultForPlaceholdersOpt?.Free(); _methodGroupReceiverMapOpt?.Free(); _placeholderLocalsOpt?.Free(); _variables.Free(); Debug.Assert(_targetTypedAnalysisCompletionOpt is null or { Count: 0 }); _targetTypedAnalysisCompletionOpt?.Free(); base.Free(); } private NullableWalker( CSharpCompilation compilation, Symbol? symbol, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, BoundNode node, Binder binder, Conversions conversions, Variables? variables, MethodSymbol? baseOrThisInitializer, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, bool isSpeculative = false) : base(compilation, symbol, node, EmptyStructTypeCache.CreatePrecise(), trackUnassignments: true) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethodOpt is object); Debug.Assert(baseOrThisInitializer is null or { MethodKind: MethodKind.Constructor }); _variables = variables ?? Variables.Create(symbol); _binder = binder; _conversions = (Conversions)conversions.WithNullability(true); _useConstructorExitWarnings = useConstructorExitWarnings; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; _delegateInvokeMethod = delegateInvokeMethodOpt; _analyzedNullabilityMapOpt = analyzedNullabilityMapOpt; _returnTypesOpt = returnTypesOpt; _snapshotBuilderOpt = snapshotBuilderOpt; _isSpeculative = isSpeculative; _hasInitialState = variables is { }; _baseOrThisInitializer = baseOrThisInitializer; } public string GetDebuggerDisplay() { if (this.IsConditionalState) { return $"{{{GetType().Name} WhenTrue:{Dump(StateWhenTrue)} WhenFalse:{Dump(StateWhenFalse)}{"}"}"; } else { return $"{{{GetType().Name} {Dump(State)}{"}"}"; } } // For purpose of nullability analysis, awaits create pending branches, so async usings and foreachs do too public sealed override bool AwaitUsingAndForeachAddsPendingBranch => true; protected override void EnsureSufficientExecutionStack(int recursionDepth) { if (recursionDepth > StackGuard.MaxUncheckedRecursionDepth && compilation.TestOnlyCompilationData is NullableAnalysisData { MaxRecursionDepth: var depth } && depth > 0 && recursionDepth > depth) { throw new InsufficientExecutionStackException(); } base.EnsureSufficientExecutionStack(recursionDepth); } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return true; } protected override bool TryGetVariable(VariableIdentifier identifier, out int slot) { return _variables.TryGetValue(identifier, out slot); } protected override int AddVariable(VariableIdentifier identifier) { return _variables.Add(identifier); } [Conditional("DEBUG")] private void AssertNoPlaceholderReplacements() { if (_resultForPlaceholdersOpt is not null) { Debug.Assert(_resultForPlaceholdersOpt.Count == 0); } } private void AddPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression? expression, VisitResult result) { #if DEBUG Debug.Assert(AreCloseEnough(placeholder.Type, result.RValueType.Type)); Debug.Assert(expression != null || placeholder.Kind == BoundKind.InterpolatedStringArgumentPlaceholder); #endif _resultForPlaceholdersOpt ??= PooledDictionary<BoundValuePlaceholderBase, (BoundExpression? Replacement, VisitResult Result)>.GetInstance(); _resultForPlaceholdersOpt.Add(placeholder, (expression, result)); } private void RemovePlaceholderReplacement(BoundValuePlaceholderBase placeholder) { Debug.Assert(_resultForPlaceholdersOpt is { }); bool removed = _resultForPlaceholdersOpt.Remove(placeholder); Debug.Assert(removed); } [Conditional("DEBUG")] private static void AssertPlaceholderAllowedWithoutRegistration(BoundValuePlaceholderBase placeholder) { Debug.Assert(placeholder is { }); switch (placeholder.Kind) { case BoundKind.DeconstructValuePlaceholder: case BoundKind.InterpolatedStringHandlerPlaceholder: case BoundKind.InterpolatedStringArgumentPlaceholder: case BoundKind.ObjectOrCollectionValuePlaceholder: case BoundKind.AwaitableValuePlaceholder: return; case BoundKind.ImplicitIndexerValuePlaceholder: // Since such placeholders are always not-null, we skip adding them to the map. return; default: // Newer placeholders are expected to follow placeholder discipline, namely that // they must be added to the map before they are visited, then removed. throw ExceptionUtilities.UnexpectedValue(placeholder.Kind); } } protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion) { if (_returnTypesOpt != null) { _returnTypesOpt.Clear(); } this.Diagnostics.Clear(); this.regionPlace = RegionPlace.Before; if (!_isSpeculative) { ParameterSymbol methodThisParameter = MethodThisParameter; EnterParameters(); // assign parameters if (methodThisParameter is object) { EnterParameter(methodThisParameter, methodThisParameter.TypeWithAnnotations); } makeNotNullMembersMaybeNull(); // We need to create a snapshot even of the first node, because we want to have the state of the initial parameters. _snapshotBuilderOpt?.TakeIncrementalSnapshot(methodMainNode, State); } ImmutableArray<PendingBranch> pendingReturns = base.Scan(ref badRegion); if ((_symbol as MethodSymbol)?.IsConstructor() != true || _useConstructorExitWarnings) { EnforceDoesNotReturn(syntaxOpt: null); enforceMemberNotNull(syntaxOpt: null, this.State); EnforceParameterNotNullOnExit(syntaxOpt: null, this.State); foreach (var pendingReturn in pendingReturns) { enforceMemberNotNull(syntaxOpt: pendingReturn.Branch.Syntax, pendingReturn.State); if (pendingReturn.Branch is BoundReturnStatement returnStatement) { EnforceParameterNotNullOnExit(returnStatement.Syntax, pendingReturn.State); EnforceNotNullWhenForPendingReturn(pendingReturn, returnStatement); enforceMemberNotNullWhenForPendingReturn(pendingReturn, returnStatement); } } } return pendingReturns; void enforceMemberNotNull(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } var method = _symbol as MethodSymbol; if (method is object) { if (method.IsConstructor()) { Debug.Assert(_useConstructorExitWarnings); var thisSlot = 0; if (method.RequiresInstanceReceiver) { method.TryGetThisParameter(out var thisParameter); Debug.Assert(thisParameter is object); thisSlot = GetOrCreateSlot(thisParameter); } // https://github.com/dotnet/roslyn/issues/46718: give diagnostics on return points, not constructor signature var exitLocation = method.DeclaringSyntaxReferences.IsEmpty ? null : method.Locations.FirstOrDefault(); foreach (var member in method.ContainingType.GetMembersUnordered()) { checkMemberStateOnConstructorExit(method, member, state, thisSlot, exitLocation); } } else { do { foreach (var memberName in method.NotNullMembers) { enforceMemberNotNullOnMember(syntaxOpt, state, method, memberName); } method = method.OverriddenMethod; } while (method != null); } } } void checkMemberStateOnConstructorExit(MethodSymbol constructor, Symbol member, LocalState state, int thisSlot, Location? exitLocation) { var isStatic = !constructor.RequiresInstanceReceiver(); if (member.IsStatic != isStatic) { return; } // This is not required for correctness, but in the case where the member has // an initializer, we know we've assigned to the member and // have given any applicable warnings about a bad value going in. // Therefore we skip this check when the member has an initializer to reduce noise. if (HasInitializer(member)) { return; } TypeWithAnnotations fieldType; FieldSymbol? field; Symbol symbol; switch (member) { case FieldSymbol f: fieldType = f.TypeWithAnnotations; field = f; symbol = (Symbol?)(f.AssociatedSymbol as PropertySymbol) ?? f; break; case EventSymbol e: fieldType = e.TypeWithAnnotations; field = e.AssociatedField; symbol = e; if (field is null) { return; } break; default: return; } if (field.IsConst) { return; } if (fieldType.Type.IsValueType || fieldType.Type.IsErrorType()) { return; } if (symbol.IsRequired() && constructor.ShouldCheckRequiredMembers()) { return; } var annotations = symbol.GetFlowAnalysisAnnotations(); if ((annotations & FlowAnalysisAnnotations.AllowNull) != 0) { // We assume that if a member has AllowNull then the user // does not care that we exit at a point where the member might be null. return; } fieldType = ApplyUnconditionalAnnotations(fieldType, annotations); if (!fieldType.NullableAnnotation.IsNotAnnotated()) { return; } var slot = GetOrCreateSlot(symbol, thisSlot); if (slot < 0) { return; } var memberState = state[slot]; var badState = fieldType.Type.IsPossiblyNullableReferenceTypeTypeParameter() && (annotations & FlowAnalysisAnnotations.NotNull) == 0 ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; if (memberState >= badState) // is 'memberState' as bad as or worse than 'badState'? { var info = new CSDiagnosticInfo(ErrorCode.WRN_UninitializedNonNullableField, new object[] { symbol.Kind.Localize(), symbol.Name }, ImmutableArray<Symbol>.Empty, additionalLocations: symbol.Locations); Diagnostics.Add(info, exitLocation ?? symbol.Locations.FirstOrNone()); } } void enforceMemberNotNullOnMember(SyntaxNode? syntaxOpt, LocalState state, MethodSymbol method, string memberName) { foreach (var member in method.ContainingType.GetMembers(memberName)) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_MemberNotNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name); } } } void enforceMemberNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } if (_symbol is MethodSymbol method) { foreach (var memberName in method.NotNullWhenTrueMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: true, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenTrue, pendingReturn.StateWhenFalse); } foreach (var memberName in method.NotNullWhenFalseMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: false, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenFalse, pendingReturn.StateWhenTrue); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); } } void enforceMemberNotNullWhenIfAffected(SyntaxNode? syntaxOpt, bool sense, ImmutableArray<Symbol> members, LocalState state, LocalState otherState) { foreach (var member in members) { // For non-constant values, only complain if we were able to analyze a difference for this member between two branches if (memberHasBadState(member, state) != memberHasBadState(member, otherState)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } void enforceMemberNotNullWhen(SyntaxNode? syntaxOpt, bool sense, LocalState state) { if (_symbol is MethodSymbol method) { var notNullMembers = sense ? method.NotNullWhenTrueMembers : method.NotNullWhenFalseMembers; foreach (var memberName in notNullMembers) { foreach (var member in method.ContainingType.GetMembers(memberName)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } } void reportMemberIfBadConditionalState(SyntaxNode? syntaxOpt, bool sense, Symbol member, LocalState state) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_MemberNotNullWhen, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name, sense ? "true" : "false"); } } bool memberHasBadState(Symbol member, LocalState state) { switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { var parameterState = state[memberSlot]; return !parameterState.IsNotNull(); } else { return false; } case SymbolKind.Event: case SymbolKind.Method: break; } return false; } void makeNotNullMembersMaybeNull() { if (_symbol is MethodSymbol method) { if (method.IsConstructor()) { foreach (var member in getMembersNeedingDefaultInitialState()) { if (member.IsStatic != method.IsStatic) { continue; } var memberToInitialize = member; switch (member) { case PropertySymbol: // skip any manually implemented properties. continue; case FieldSymbol { IsConst: true }: continue; case FieldSymbol { AssociatedSymbol: PropertySymbol prop }: // this is a property where assigning 'default' causes us to simply update // the state to the output state of the property // thus we skip setting an initial state for it here if (IsPropertyOutputMoreStrictThanInput(prop)) { continue; } // We want to initialize auto-property state to the default state, but not computed properties. memberToInitialize = prop; break; default: break; } var memberSlot = getSlotForFieldOrPropertyOrEvent(memberToInitialize); if (memberSlot > 0) { var type = memberToInitialize.GetTypeOrReturnType(); if (!type.NullableAnnotation.IsOblivious()) { this.State[memberSlot] = type.Type.IsPossiblyNullableReferenceTypeTypeParameter() ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } } else { do { makeMembersMaybeNull(method, method.NotNullMembers); makeMembersMaybeNull(method, method.NotNullWhenTrueMembers); makeMembersMaybeNull(method, method.NotNullWhenFalseMembers); method = method.OverriddenMethod; } while (method != null); } } return; ImmutableArray<Symbol> getMembersNeedingDefaultInitialState() { if (_hasInitialState) { return ImmutableArray<Symbol>.Empty; } bool includeCurrentTypeRequiredMembers = true; bool includeBaseRequiredMembers = true; bool hasThisConstructorInitializer = false; if (method is SourceMemberMethodSymbol { SyntaxNode: ConstructorDeclarationSyntax { Initializer: { RawKind: var initializerKind } } }) { // We have multiple ways of entering the nullable walker: we could be just analyzing the initializers, with a BoundStatementList body and _baseOrThisInitializer // having been provided, or we could be analyzing the body of a constructor, with a BoundConstructorBody body and _baseOrThisInitializer being null. var baseOrThisInitializer = (_baseOrThisInitializer ?? GetConstructorThisOrBaseSymbol(this.methodMainNode)); // If there's an error in the base or this initializer, presume that we should set all required members to default. includeBaseRequiredMembers = baseOrThisInitializer?.ShouldCheckRequiredMembers() ?? true; if (initializerKind == (int)SyntaxKind.ThisConstructorInitializer) { hasThisConstructorInitializer = true; // If we chained to a `this` constructor, a SetsRequiredMembers attribute applies to both the current type's required members and the base type's required members. includeCurrentTypeRequiredMembers = includeBaseRequiredMembers; } else if (initializerKind == (int)SyntaxKind.BaseConstructorInitializer) { // If we chained to a `base` constructor, a SetsRequiredMembers attribute applies to the base type's required members only, and the current type's required members // are not assumed to be initialized. includeCurrentTypeRequiredMembers = true; } } // Pre-C# 11, we don't use a default initial state for value type instance constructors without `: this()` // because any usages of uninitialized fields will get definite assignment errors anyway. if (!hasThisConstructorInitializer && (!method.ContainingType.IsValueType || method.IsStatic || compilation.IsFeatureEnabled(MessageID.IDS_FeatureAutoDefaultStructs))) { return membersToBeInitialized(method.ContainingType, includeAllMembers: true, includeCurrentTypeRequiredMembers, includeBaseRequiredMembers); } // We want to presume all required members of the type are uninitialized, and in addition we want to set all fields to // default if we can get to this constructor by doing so (ie, : this() in a value type). return membersToBeInitialized(method.ContainingType, includeAllMembers: method.IncludeFieldInitializersInBody(), includeCurrentTypeRequiredMembers, includeBaseRequiredMembers); static ImmutableArray<Symbol> membersToBeInitialized(NamedTypeSymbol containingType, bool includeAllMembers, bool includeCurrentTypeRequiredMembers, bool includeBaseRequiredMembers) { return (includeAllMembers, includeCurrentTypeRequiredMembers, includeBaseRequiredMembers) switch { (includeAllMembers: false, includeCurrentTypeRequiredMembers: false, includeBaseRequiredMembers: false) => ImmutableArray<Symbol>.Empty, (includeAllMembers: false, includeCurrentTypeRequiredMembers: true, includeBaseRequiredMembers: false) => containingType.GetMembersUnordered().SelectAsArray(predicate: SymbolExtensions.IsRequired, selector: getFieldSymbolToBeInitialized), (includeAllMembers: false, includeCurrentTypeRequiredMembers: true, includeBaseRequiredMembers: true) => containingType.AllRequiredMembers.SelectAsArray(static kvp => getFieldSymbolToBeInitialized(kvp.Value)), (includeAllMembers: true, includeCurrentTypeRequiredMembers: _, includeBaseRequiredMembers: false) => containingType.GetMembersUnordered().SelectAsArray(getFieldSymbolToBeInitialized), (includeAllMembers: true, includeCurrentTypeRequiredMembers: true, includeBaseRequiredMembers: true) => getAllTypeAndRequiredMembers(containingType), (includeAllMembers: _, includeCurrentTypeRequiredMembers: false, includeBaseRequiredMembers: true) => throw ExceptionUtilities.Unreachable, }; static ImmutableArray<Symbol> getAllTypeAndRequiredMembers(TypeSymbol containingType) { var members = containingType.GetMembersUnordered(); var requiredMembers = containingType.BaseTypeNoUseSiteDiagnostics?.AllRequiredMembers ?? ImmutableSegmentedDictionary<string, Symbol>.Empty; if (requiredMembers.IsEmpty) { return members; } var builder = ArrayBuilder<Symbol>.GetInstance(members.Length + requiredMembers.Count); builder.AddRange(members); foreach (var (_, requiredMember) in requiredMembers) { // We want to assume that all required members were _not_ set by the chained constructor builder.Add(getFieldSymbolToBeInitialized(requiredMember)); } return builder.ToImmutableAndFree(); } static Symbol getFieldSymbolToBeInitialized(Symbol requiredMember) => requiredMember is SourcePropertySymbol { IsAutoPropertyWithGetAccessor: true } prop ? prop.BackingField : requiredMember; } } } void makeMembersMaybeNull(MethodSymbol method, ImmutableArray<string> members) { foreach (var memberName in members) { makeMemberMaybeNull(method, memberName); } } void makeMemberMaybeNull(MethodSymbol method, string memberName) { var type = method.ContainingType; foreach (var member in type.GetMembers(memberName)) { if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { this.State[memberSlot] = NullableFlowState.MaybeNull; } } } int getSlotForFieldOrPropertyOrEvent(Symbol member) { if (member.Kind != SymbolKind.Field && member.Kind != SymbolKind.Property && member.Kind != SymbolKind.Event) { return -1; } int containingSlot = 0; if (!member.IsStatic) { if (MethodThisParameter is null) { return -1; } containingSlot = GetOrCreateSlot(MethodThisParameter); if (containingSlot < 0) { return -1; } Debug.Assert(containingSlot > 0); } return GetOrCreateSlot(member, containingSlot); } } private void EnforceNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { var parameters = this.MethodParameters; if (!parameters.IsEmpty) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { EnforceParameterNotNullWhenOnExit(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } foreach (var parameter in parameters) { // For non-constant values, only complain if we were able to analyze a difference for this parameter between two branches if (GetOrCreateSlot(parameter) is > 0 and var slot && pendingReturn.StateWhenTrue[slot] != pendingReturn.StateWhenFalse[slot]) { ReportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: true, stateWhen: pendingReturn.StateWhenTrue); ReportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: false, stateWhen: pendingReturn.StateWhenFalse); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { // example: return (bool)true; EnforceParameterNotNullWhenOnExit(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } } } private void EnforceParameterNotNullOnExit(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } foreach (var parameter in this.MethodParameters) { var slot = GetOrCreateSlot(parameter); if (slot <= 0) { continue; } var annotations = parameter.FlowAnalysisAnnotations; var hasNotNull = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; var parameterState = state[slot]; if (hasNotNull && parameterState.MayBeNull()) { Location location; if (syntaxOpt is BlockSyntax blockSyntax) { location = blockSyntax.CloseBraceToken.GetLocation(); } else { location = syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(); } // Parameter '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_ParameterDisallowsNull, location, parameter.Name); } else { EnforceNotNullIfNotNull(syntaxOpt, state, this.MethodParameters, parameter.NotNullIfParameterNotNull, parameterState, parameter); } } } private void EnforceParameterNotNullWhenOnExit(SyntaxNode syntax, ImmutableArray<ParameterSymbol> parameters, bool sense, LocalState stateWhen) { if (!stateWhen.Reachable) { return; } foreach (var parameter in parameters) { ReportParameterIfBadConditionalState(syntax, parameter, sense, stateWhen); } } private void ReportParameterIfBadConditionalState(SyntaxNode syntax, ParameterSymbol parameter, bool sense, LocalState stateWhen) { if (parameterHasBadConditionalState(parameter, sense, stateWhen)) { // Parameter '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_ParameterConditionallyDisallowsNull, syntax.Location, parameter.Name, sense ? "true" : "false"); } return; bool parameterHasBadConditionalState(ParameterSymbol parameter, bool sense, LocalState stateWhen) { var refKind = parameter.RefKind; if (refKind != RefKind.Out && refKind != RefKind.Ref) { return false; } var slot = GetOrCreateSlot(parameter); if (slot > 0) { var parameterState = stateWhen[slot]; // On a parameter marked with MaybeNullWhen, we would have not reported an assignment warning. // We should only check if an assignment warning would have been warranted ignoring the MaybeNullWhen. FlowAnalysisAnnotations annotations = parameter.FlowAnalysisAnnotations; if (sense) { bool hasNotNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenTrue; bool hasMaybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenFalse; return (hasNotNullWhenTrue && parameterState.MayBeNull()) || (hasMaybeNullWhenFalse && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } else { bool hasNotNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenFalse; bool hasMaybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenTrue; return (hasNotNullWhenFalse && parameterState.MayBeNull()) || (hasMaybeNullWhenTrue && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } } return false; } } private void EnforceNotNullIfNotNull(SyntaxNode? syntaxOpt, LocalState state, ImmutableArray<ParameterSymbol> parameters, ImmutableHashSet<string> inputParamNames, NullableFlowState outputState, ParameterSymbol? outputParam) { if (inputParamNames.IsEmpty || outputState.IsNotNull()) { return; } foreach (var inputParam in parameters) { if (inputParamNames.Contains(inputParam.Name) && GetOrCreateSlot(inputParam) is > 0 and int inputSlot && state[inputSlot].IsNotNull()) { var location = syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(); if (outputParam is object) { // Parameter '{0}' must have a non-null value when exiting because parameter '{1}' is non-null. Diagnostics.Add(ErrorCode.WRN_ParameterNotNullIfNotNull, location, outputParam.Name, inputParam.Name); } else if (CurrentSymbol is MethodSymbol { IsAsync: false }) { // Return value must be non-null because parameter '{0}' is non-null. Diagnostics.Add(ErrorCode.WRN_ReturnNotNullIfNotNull, location, inputParam.Name); } break; } } } private void EnforceDoesNotReturn(SyntaxNode? syntaxOpt) { if (CurrentSymbol is MethodSymbol method && ((method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) && this.IsReachable()) { // A method marked [DoesNotReturn] should not return. ReportDiagnostic(ErrorCode.WRN_ShouldNotReturn, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation()); } } /// <summary> /// Analyzes a method body if settings indicate we should. /// </summary> internal static void AnalyzeIfNeeded( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, MethodSymbol? baseOrThisInitializer, out VariableState? finalNullableState) { if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(method)) { if (compilation.IsNullableAnalysisEnabledAlways) { // Once we address https://github.com/dotnet/roslyn/issues/46579 we should also always pass `getFinalNullableState: true` in debug mode. // We will likely always need to write a 'null' out for the out parameter in this code path, though, because // we don't want to introduce behavior differences between debug and release builds Analyze(compilation, method, node, new DiagnosticBag(), useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: false, baseOrThisInitializer, out _, requiresAnalysis: false); } finalNullableState = null; return; } Analyze(compilation, method, node, diagnostics, useConstructorExitWarnings, initialNullableState, getFinalNullableState, baseOrThisInitializer, out finalNullableState); } private static void Analyze( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, MethodSymbol? baseOrThisInitializer, out VariableState? finalNullableState, bool requiresAnalysis = true) { if (method.IsImplicitlyDeclared && !method.IsImplicitConstructor && !method.IsScriptInitializer) { finalNullableState = null; return; } Debug.Assert(node.SyntaxTree is object); var binder = method is SynthesizedSimpleProgramEntryPointSymbol entryPoint ? entryPoint.GetBodyBinder(ignoreAccessibility: false) : compilation.GetBinderFactory(node.SyntaxTree).GetBinder(node.Syntax); var conversions = binder.Conversions; Analyze(compilation, method, node, binder, conversions, diagnostics, useConstructorExitWarnings, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: initialNullableState, baseOrThisInitializer, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState, finalNullableState: out finalNullableState, requiresAnalysis); } internal static VariableState? GetAfterInitializersState(CSharpCompilation compilation, Symbol? symbol, BoundNode constructorBody) { if (symbol is MethodSymbol method && method.IncludeFieldInitializersInBody() && method.ContainingType is SourceMemberContainerTypeSymbol containingType) { Binder.ProcessedFieldInitializers discardedInitializers = default; Binder.BindFieldInitializers(compilation, null, method.IsStatic ? containingType.StaticInitializers : containingType.InstanceInitializers, BindingDiagnosticBag.Discarded, ref discardedInitializers); return GetAfterInitializersState(compilation, method, InitializerRewriter.RewriteConstructor(discardedInitializers.BoundInitializers, method), constructorBody, diagnostics: BindingDiagnosticBag.Discarded); } return null; } /// <summary> /// Gets the "after initializers state" which should be used at the beginning of nullable analysis /// of certain constructors. /// </summary> internal static VariableState? GetAfterInitializersState(CSharpCompilation compilation, MethodSymbol method, BoundNode nodeToAnalyze, BoundNode? constructorBody, BindingDiagnosticBag diagnostics) { Debug.Assert(method.IsConstructor()); bool ownsDiagnostics; DiagnosticBag diagnosticsBag; if (diagnostics.DiagnosticBag == null) { diagnostics = BindingDiagnosticBag.Discarded; diagnosticsBag = DiagnosticBag.GetInstance(); ownsDiagnostics = true; } else { diagnosticsBag = diagnostics.DiagnosticBag; ownsDiagnostics = false; } MethodSymbol? baseOrThisInitializer = GetConstructorThisOrBaseSymbol(constructorBody); NullableWalker.AnalyzeIfNeeded( compilation, method, nodeToAnalyze, diagnosticsBag, useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: true, baseOrThisInitializer, out var afterInitializersState); if (ownsDiagnostics) { diagnosticsBag.Free(); } return afterInitializersState; } private static MethodSymbol? GetConstructorThisOrBaseSymbol(BoundNode? constructorBody) { return constructorBody is BoundConstructorMethodBody { Initializer: BoundExpressionStatement { Expression: BoundCall { Method: { MethodKind: MethodKind.Constructor } initializerMethod } } } ? initializerMethod : null; } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information. This method is only /// used when nullable is explicitly enabled for all methods but disabled otherwise to verify that /// correct semantic information is being recorded for all bound nodes. The results are thrown away. /// </summary> internal static void AnalyzeWithoutRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, DiagnosticBag diagnostics, bool createSnapshots) { _ = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState: GetAfterInitializersState(compilation, symbol, node), diagnostics, createSnapshots, requiresAnalysis: false); } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information, and returns an /// updated BoundNode with the information populated. /// </summary> internal static BoundNode AnalyzeAndRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, out SnapshotManager? snapshotManager, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> analyzedNullabilitiesMap; (snapshotManager, analyzedNullabilitiesMap) = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState, diagnostics, createSnapshots, requiresAnalysis: true); return Rewrite(analyzedNullabilitiesMap, snapshotManager, node, ref remappedSymbols); } private static (SnapshotManager?, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>) AnalyzeWithSemanticInfo( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, bool requiresAnalysis) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); // Attributes don't have a symbol, which is what SnapshotBuilder uses as an index for maintaining global state. // Until we have a workaround for this, disable snapshots for null symbols. // https://github.com/dotnet/roslyn/issues/36066 var snapshotBuilder = createSnapshots && symbol != null ? new SnapshotManager.Builder() : null; Analyze( compilation, symbol, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: true, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState, baseOrThisInitializer: null, analyzedNullabilities, snapshotBuilder, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); var snapshotManager = snapshotBuilder?.ToManagerAndFree(); #if DEBUG // https://github.com/dotnet/roslyn/issues/34993 Enable for all calls if (isNullableAnalysisEnabledAnywhere(compilation)) { DebugVerifier.Verify(analyzedNullabilitiesMap, snapshotManager, node); } static bool isNullableAnalysisEnabledAnywhere(CSharpCompilation compilation) { if (compilation.Options.NullableContextOptions != NullableContextOptions.Disable) { return true; } return compilation.SyntaxTrees.Any(static tree => ((CSharpSyntaxTree)tree).IsNullableAnalysisEnabled(new Text.TextSpan(0, tree.Length)) == true); } #endif return (snapshotManager, analyzedNullabilitiesMap); } internal static BoundNode AnalyzeAndRewriteSpeculation( int position, BoundNode node, Binder binder, SnapshotManager originalSnapshots, out SnapshotManager newSnapshots, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); var newSnapshotBuilder = new SnapshotManager.Builder(); var (variables, localState) = originalSnapshots.GetSnapshot(position); var symbol = variables.Symbol; var walker = new NullableWalker( binder.Compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, binder.Conversions, Variables.Create(variables), baseOrThisInitializer: null, returnTypesOpt: null, analyzedNullabilities, newSnapshotBuilder, isSpeculative: true); try { Analyze(walker, symbol, diagnostics: null, LocalState.Create(localState), snapshotBuilderOpt: newSnapshotBuilder); } finally { walker.Free(); } var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); newSnapshots = newSnapshotBuilder.ToManagerAndFree(); #if DEBUG DebugVerifier.Verify(analyzedNullabilitiesMap, newSnapshots, node); #endif return Rewrite(analyzedNullabilitiesMap, newSnapshots, node, ref remappedSymbols); } private static BoundNode Rewrite(ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> updatedNullabilities, SnapshotManager? snapshotManager, BoundNode node, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var remappedSymbolsBuilder = ImmutableDictionary.CreateBuilder<Symbol, Symbol>(Symbols.SymbolEqualityComparer.ConsiderEverything, Symbols.SymbolEqualityComparer.ConsiderEverything); if (remappedSymbols is object) { // When we're rewriting for the speculative model, there will be a set of originally-mapped symbols, and we need to // use them in addition to any symbols found during this pass of the walker. remappedSymbolsBuilder.AddRange(remappedSymbols); } var rewriter = new NullabilityRewriter(updatedNullabilities, snapshotManager, remappedSymbolsBuilder); var rewrittenNode = rewriter.Visit(node); remappedSymbols = remappedSymbolsBuilder.ToImmutable(); return rewrittenNode; } private static bool HasRequiredLanguageVersion(CSharpCompilation compilation) { return compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion(); } /// <summary> /// Returns true if the nullable analysis is needed for the region represented by <paramref name="syntaxNode"/>. /// The syntax node is used to determine the overall nullable context for the region. /// </summary> internal static bool NeedsAnalysis(CSharpCompilation compilation, SyntaxNode syntaxNode) { return HasRequiredLanguageVersion(compilation) && (compilation.IsNullableAnalysisEnabledIn(syntaxNode) || compilation.IsNullableAnalysisEnabledAlways); } /// <summary>Analyzes a node in a "one-off" context, such as for attributes or parameter default values.</summary> /// <remarks><paramref name="syntax"/> is the syntax span used to determine the overall nullable context.</remarks> internal static void AnalyzeIfNeeded( Binder binder, BoundNode node, SyntaxNode syntax, DiagnosticBag diagnostics) { bool requiresAnalysis = true; var compilation = binder.Compilation; if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(syntax)) { if (!compilation.IsNullableAnalysisEnabledAlways) { return; } diagnostics = new DiagnosticBag(); requiresAnalysis = false; } Analyze( compilation, symbol: null, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: null, baseOrThisInitializer: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); } internal static void Analyze( CSharpCompilation compilation, BoundLambda lambda, Conversions conversions, DiagnosticBag diagnostics, MethodSymbol? delegateInvokeMethodOpt, VariableState initialState, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt) { var symbol = lambda.Symbol; var variables = Variables.Create(initialState.Variables).CreateNestedMethodScope(symbol); UseDelegateInvokeParameterAndReturnTypes(lambda, delegateInvokeMethodOpt, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); var walker = new NullableWalker( compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: useDelegateInvokeParameterTypes, useDelegateInvokeReturnType: useDelegateInvokeReturnType, delegateInvokeMethodOpt: delegateInvokeMethodOpt, lambda.Body, lambda.Binder, conversions, variables, baseOrThisInitializer: null, returnTypesOpt, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); try { var localState = LocalState.Create(initialState.VariableNullableStates).CreateNestedMethodState(variables); Analyze(walker, symbol, diagnostics, localState, snapshotBuilderOpt: null); } finally { walker.Free(); } } private static void Analyze( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, Conversions conversions, DiagnosticBag diagnostics, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, VariableState? initialState, MethodSymbol? baseOrThisInitializer, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) { Debug.Assert(diagnostics != null); var walker = new NullableWalker(compilation, symbol, useConstructorExitWarnings, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType, delegateInvokeMethodOpt, node, binder, conversions, initialState is null ? null : Variables.Create(initialState.Variables), baseOrThisInitializer, returnTypesOpt, analyzedNullabilityMapOpt, snapshotBuilderOpt); finalNullableState = null; try { Analyze(walker, symbol, diagnostics, initialState is null ? (Optional<LocalState>)default : LocalState.Create(initialState.VariableNullableStates), snapshotBuilderOpt, requiresAnalysis); if (getFinalNullableState) { Debug.Assert(!walker.IsConditionalState); finalNullableState = GetVariableState(walker._variables, walker.State); } } finally { walker.Free(); } } private static void Analyze( NullableWalker walker, Symbol? symbol, DiagnosticBag? diagnostics, Optional<LocalState> initialState, SnapshotManager.Builder? snapshotBuilderOpt, bool requiresAnalysis = true) { Debug.Assert(snapshotBuilderOpt is null || symbol is object); var previousSlot = snapshotBuilderOpt?.EnterNewWalker(symbol!) ?? -1; try { bool badRegion = false; ImmutableArray<PendingBranch> returns = walker.Analyze(ref badRegion, initialState); diagnostics?.AddRange(walker.Diagnostics); Debug.Assert(!badRegion); } catch (CancelledByStackGuardException ex) when (diagnostics != null) { ex.AddAnError(diagnostics); } finally { snapshotBuilderOpt?.ExitWalker(walker.SaveSharedState(), previousSlot); } walker.RecordNullableAnalysisData(symbol, requiresAnalysis); } private void RecordNullableAnalysisData(Symbol? symbol, bool requiredAnalysis) { if (compilation.TestOnlyCompilationData is NullableAnalysisData { Data: { } state }) { var key = (object?)symbol ?? methodMainNode.Syntax; if (state.TryGetValue(key, out var result)) { Debug.Assert(result.RequiredAnalysis == requiredAnalysis); } else { state.TryAdd(key, new Data(_variables.GetTotalVariableCount(), requiredAnalysis)); } } } private SharedWalkerState SaveSharedState() { return new SharedWalkerState(_variables.CreateSnapshot()); } private void TakeIncrementalSnapshot(BoundNode? node) { Debug.Assert(!IsConditionalState); _snapshotBuilderOpt?.TakeIncrementalSnapshot(node, State); } private void SetUpdatedSymbol(BoundNode node, Symbol originalSymbol, Symbol updatedSymbol) { if (_snapshotBuilderOpt is null) { return; } var lambdaIsExactMatch = false; if (node is BoundLambda boundLambda && originalSymbol is LambdaSymbol l && updatedSymbol is NamedTypeSymbol n) { if (!AreLambdaAndNewDelegateSimilar(l, n)) { return; } lambdaIsExactMatch = updatedSymbol.Equals(boundLambda.Type!.GetDelegateType(), TypeCompareKind.ConsiderEverything); } #if DEBUG Debug.Assert(node is object); Debug.Assert(AreCloseEnough(originalSymbol, updatedSymbol), $"Attempting to set {node.Syntax} from {originalSymbol.ToDisplayString()} to {updatedSymbol.ToDisplayString()}"); #endif if (lambdaIsExactMatch || Symbol.Equals(originalSymbol, updatedSymbol, TypeCompareKind.ConsiderEverything)) { // If the symbol is reset, remove the updated symbol so we don't needlessly update the // bound node later on. We do this unconditionally, as Remove will just return false // if the key wasn't in the dictionary. _snapshotBuilderOpt.RemoveSymbolIfPresent(node, originalSymbol); } else { _snapshotBuilderOpt.SetUpdatedSymbol(node, originalSymbol, updatedSymbol); } } protected override void Normalize(ref LocalState state) { if (!state.Reachable) return; state.Normalize(this, _variables); } private NullableFlowState GetDefaultState(ref LocalState state, int slot) { Debug.Assert(slot > 0); if (!state.Reachable) return NullableFlowState.NotNull; var variable = _variables[slot]; var symbol = variable.Symbol; switch (symbol.Kind) { case SymbolKind.Local: { var local = (LocalSymbol)symbol; if (!_variables.TryGetType(local, out TypeWithAnnotations localType)) { localType = local.TypeWithAnnotations; } return localType.ToTypeWithState().State; } case SymbolKind.Parameter: { var parameter = (ParameterSymbol)symbol; if (!_variables.TryGetType(parameter, out TypeWithAnnotations parameterType)) { parameterType = parameter.TypeWithAnnotations; } return GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; } case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: return GetDefaultState(symbol); case SymbolKind.ErrorType: return NullableFlowState.NotNull; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } protected override bool TryGetReceiverAndMember(BoundExpression expr, out BoundExpression? receiver, [NotNullWhen(true)] out Symbol? member) { receiver = null; member = null; switch (expr.Kind) { case BoundKind.FieldAccess: { var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; member = fieldSymbol; if (fieldSymbol.IsFixedSizeBuffer) { return false; } if (fieldSymbol.IsStatic) { return true; } receiver = fieldAccess.ReceiverOpt; break; } case BoundKind.EventAccess: { var eventAccess = (BoundEventAccess)expr; var eventSymbol = eventAccess.EventSymbol; // https://github.com/dotnet/roslyn/issues/29901 Use AssociatedField for field-like events? member = eventSymbol; if (eventSymbol.IsStatic) { return true; } receiver = eventAccess.ReceiverOpt; break; } case BoundKind.PropertyAccess: { var propAccess = (BoundPropertyAccess)expr; var propSymbol = propAccess.PropertySymbol; member = propSymbol; if (propSymbol.IsStatic) { return true; } receiver = propAccess.ReceiverOpt; break; } } Debug.Assert(member?.RequiresInstanceReceiver() ?? true); return member is object && receiver is object && receiver.Kind != BoundKind.TypeExpression && receiver.Type is object; } protected override int MakeSlot(BoundExpression node) { int result = makeSlot(node); #if DEBUG if (result != -1) { // Check that the slot represents a value of an equivalent type to the node TypeSymbol slotType = NominalSlotType(result); TypeSymbol? nodeType = node.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = this.compilation.Conversions; Debug.Assert(node.HasErrors || (nodeType is { } && (nodeType.IsErrorType() || conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(slotType, nodeType, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(slotType, nodeType, ref discardedUseSiteInfo)))); } #endif return result; int makeSlot(BoundExpression node) { switch (node.Kind) { case BoundKind.ThisReference: case BoundKind.BaseReference: { var method = getTopLevelMethod(_symbol as MethodSymbol); var thisParameter = method?.ThisParameter; return thisParameter is object ? GetOrCreateSlot(thisParameter) : -1; } case BoundKind.Conversion: { int slot = getPlaceholderSlot(node); if (slot > 0) { return slot; } var conv = (BoundConversion)node; switch (conv.Conversion.Kind) { case ConversionKind.ExplicitNullable: { var operand = conv.Operand; var operandType = operand.Type; var convertedType = conv.Type; if (AreNullableAndUnderlyingTypes(operandType, convertedType, out _)) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. // For instance, in the following, when evaluating `((A)a).B` we need to recognize // the nullability of `(A)a` (not nullable) and the slot (the slot for `a.Value`). // struct A { B? B; } // struct B { } // if (a?.B != null) _ = ((A)a).B.Value; // no warning int containingSlot = MakeSlot(operand); return containingSlot < 0 ? -1 : GetNullableOfTValueSlot(operandType, containingSlot, out _); } } break; case ConversionKind.ConditionalExpression or ConversionKind.SwitchExpression or ConversionKind.ObjectCreation when IsTargetTypedExpression(conv.Operand) && TypeSymbol.Equals(conv.Type, conv.Operand.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes): case ConversionKind.Identity: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.Boxing: // No need to create a slot for the boxed value (in the Boxing case) since assignment already // clones slots and there is not another scenario where creating a slot is observable. return MakeSlot(conv.Operand); } } break; case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.ObjectCreationExpression: case BoundKind.DynamicObjectCreationExpression: case BoundKind.AnonymousObjectCreationExpression: case BoundKind.NewT: case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return getPlaceholderSlot(node); case BoundKind.ConditionalAccess: return getPlaceholderSlot(node); case BoundKind.ConditionalReceiver: return _lastConditionalAccessSlot; default: { int slot = getPlaceholderSlot(node); return (slot > 0) ? slot : base.MakeSlot(node); } } return -1; } int getPlaceholderSlot(BoundExpression expr) { if (_placeholderLocalsOpt != null && _placeholderLocalsOpt.TryGetValue(expr, out var placeholder)) { return GetOrCreateSlot(placeholder); } return -1; } static MethodSymbol? getTopLevelMethod(MethodSymbol? method) { while (method is object) { var container = method.ContainingSymbol; if (container.Kind == SymbolKind.NamedType) { return method; } method = container as MethodSymbol; } return null; } } protected override int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bool forceSlotEvenIfEmpty = false, bool createIfMissing = true) { if (containingSlot > 0 && !IsSlotMember(containingSlot, symbol)) return -1; return base.GetOrCreateSlot(symbol, containingSlot, forceSlotEvenIfEmpty, createIfMissing); } private void VisitAndUnsplitAll<T>(ImmutableArray<T> nodes) where T : BoundNode { if (nodes.IsDefault) { return; } foreach (var node in nodes) { Visit(node); Unsplit(); } } private void VisitWithoutDiagnostics(BoundNode? node) { var previousDiagnostics = _disableDiagnostics; _disableDiagnostics = true; Visit(node); _disableDiagnostics = previousDiagnostics; } protected override void VisitRvalue(BoundExpression? node, bool isKnownToBeAnLvalue = false) { Visit(node); VisitRvalueEpilogue(node); } /// <summary> /// The contents of this method, particularly <see cref="UseRvalueOnly"/>, are problematic when /// inlined. The methods themselves are small but they end up allocating significantly larger /// frames due to the use of biggish value types within them. The <see cref="VisitRvalue"/> method /// is used on a hot path for fluent calls and this size change is enough that it causes us /// to exceed our thresholds in EndToEndTests.OverflowOnFluentCall. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private void VisitRvalueEpilogue(BoundExpression? node) { Unsplit(); UseRvalueOnly(node); // drop lvalue part } private TypeWithState VisitRvalueWithState(BoundExpression? node) { VisitRvalue(node); return ResultType; } private TypeWithAnnotations VisitLvalueWithAnnotations(BoundExpression node) { VisitLValue(node); Unsplit(); return LvalueResultType; } private static object GetTypeAsDiagnosticArgument(TypeSymbol? typeOpt) { return typeOpt ?? (object)"<null>"; } private static object GetParameterAsDiagnosticArgument(ParameterSymbol? parameterOpt) { return parameterOpt is null ? (object)"" : new FormattedSymbol(parameterOpt, SymbolDisplayFormat.ShortFormat); } private static object GetContainingSymbolAsDiagnosticArgument(ParameterSymbol? parameterOpt) { var containingSymbol = parameterOpt?.ContainingSymbol; return containingSymbol is null ? (object)"" : new FormattedSymbol(containingSymbol, SymbolDisplayFormat.MinimallyQualifiedFormat); } private enum AssignmentKind { Assignment, Return, Argument, ForEachIterationVariable } /// <summary> /// Should we warn for assigning this state into this type? /// /// This should often be checked together with <seealso cref="IsDisallowedNullAssignment(TypeWithState, FlowAnalysisAnnotations)"/> /// It catches putting a `null` into a `[DisallowNull]int?` for example, which cannot simply be represented as a non-nullable target type. /// </summary> private static bool ShouldReportNullableAssignment(TypeWithAnnotations type, NullableFlowState state) { if (!type.HasType || type.Type.IsValueType) { return false; } switch (type.NullableAnnotation) { case NullableAnnotation.Oblivious: case NullableAnnotation.Annotated: return false; } switch (state) { case NullableFlowState.NotNull: return false; case NullableFlowState.MaybeNull: if (type.Type.IsTypeParameterDisallowingAnnotationInCSharp8() && !(type.Type is TypeParameterSymbol { IsNotNullable: true })) { return false; } break; } return true; } /// <summary> /// Reports top-level nullability problem in assignment. /// Any conversion of the value should have been applied. /// </summary> private void ReportNullableAssignmentIfNecessary( BoundExpression? value, TypeWithAnnotations targetType, TypeWithState valueType, bool useLegacyWarnings, AssignmentKind assignmentKind = AssignmentKind.Assignment, ParameterSymbol? parameterOpt = null, Location? location = null) { // Callers should apply any conversions before calling this method // (see https://github.com/dotnet/roslyn/issues/39867). if (targetType.HasType && !targetType.Type.Equals(valueType.Type, TypeCompareKind.AllIgnoreOptions)) { return; } if (value == null || // This prevents us from giving undesired warnings for synthesized arguments for optional parameters, // but allows us to give warnings for synthesized assignments to record properties and for parameter default values at the declaration site. // Interpolated string handler argument placeholders _are_ compiler generated, but the user should be warned about them anyway. (value.WasCompilerGenerated && assignmentKind == AssignmentKind.Argument && value.Kind != BoundKind.InterpolatedStringArgumentPlaceholder) || !ShouldReportNullableAssignment(targetType, valueType.State)) { return; } location ??= value.Syntax.GetLocation(); var unwrappedValue = SkipReferenceConversions(value); if (unwrappedValue.IsSuppressed) { return; } if (value.ConstantValue?.IsNull == true && !useLegacyWarnings) { // Report warning converting null literal to non-nullable reference type. // target (e.g.: `object F() => null;` or calling `void F(object y)` with `F(null)`). ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullAsNonNullable, location); } else if (assignmentKind == AssignmentKind.Argument) { ReportDiagnostic(ErrorCode.WRN_NullReferenceArgument, location, GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); LearnFromNonNullTest(value, ref State); } else if (useLegacyWarnings) { if (isMaybeDefaultValue(valueType) && !allowUnconstrainedTypeParameterAnnotations(compilation)) { // No W warning reported assigning or casting [MaybeNull]T value to T // because there is no syntax for declaring the target type as [MaybeNull]T. return; } ReportNonSafetyDiagnostic(location); } else { ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullReferenceAssignment, location); } static bool isMaybeDefaultValue(TypeWithState valueType) { return valueType.Type?.TypeKind == TypeKind.TypeParameter && valueType.State == NullableFlowState.MaybeDefault; } static bool allowUnconstrainedTypeParameterAnnotations(CSharpCompilation compilation) { // Check IDS_FeatureDefaultTypeParameterConstraint feature since `T?` and `where ... : default` // are treated as a single feature, even though the errors reported for the two cases are distinct. var requiredVersion = MessageID.IDS_FeatureDefaultTypeParameterConstraint.RequiredVersion(); return requiredVersion <= compilation.LanguageVersion; } } internal static bool AreParameterAnnotationsCompatible( RefKind refKind, TypeWithAnnotations overriddenType, FlowAnalysisAnnotations overriddenAnnotations, TypeWithAnnotations overridingType, FlowAnalysisAnnotations overridingAnnotations, bool forRef = false) { // We've already checked types and annotations, let's check nullability attributes as well // Return value is treated as an `out` parameter (or `ref` if it is a `ref` return) if (refKind == RefKind.Ref) { // ref variables are invariant return AreParameterAnnotationsCompatible(RefKind.None, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations, forRef: true) && AreParameterAnnotationsCompatible(RefKind.Out, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations); } if (refKind == RefKind.None || refKind == RefKind.In) { // pre-condition attributes // Check whether we can assign a value from overridden parameter to overriding var valueState = GetParameterState( overriddenType, overriddenAnnotations); if (isBadAssignment(valueState, overridingType, overridingAnnotations)) { return false; } // unconditional post-condition attributes on inputs bool overridingHasNotNull = (overridingAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; bool overriddenHasNotNull = (overriddenAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; if (overriddenHasNotNull && !overridingHasNotNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise not to return if parameter is null) return false; } bool overridingHasMaybeNull = (overridingAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; bool overriddenHasMaybeNull = (overriddenAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; if (overriddenHasMaybeNull && !overridingHasMaybeNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise to only return if parameter is null) return false; } } if (refKind == RefKind.Out) { // post-condition attributes (`Maybe/NotNull` and `Maybe/NotNullWhen`) if (!canAssignOutputValueWhen(true) || !canAssignOutputValueWhen(false)) { return false; } } return true; bool canAssignOutputValueWhen(bool sense) { var valueWhen = ApplyUnconditionalAnnotations( overridingType.ToTypeWithState(), makeUnconditionalAnnotation(overridingAnnotations, sense)); var destAnnotationsWhen = ToInwardAnnotations(makeUnconditionalAnnotation(overriddenAnnotations, sense)); if (isBadAssignment(valueWhen, overriddenType, destAnnotationsWhen)) { // Can't assign value from overriding to overridden in 'sense' case return false; } return true; } static bool isBadAssignment(TypeWithState valueState, TypeWithAnnotations destinationType, FlowAnalysisAnnotations destinationAnnotations) { if (ShouldReportNullableAssignment( ApplyLValueAnnotations(destinationType, destinationAnnotations), valueState.State)) { return true; } if (IsDisallowedNullAssignment(valueState, destinationAnnotations)) { return true; } return false; } // Convert both conditional annotations to unconditional ones or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotation(FlowAnalysisAnnotations annotations, bool sense) { if (sense) { var unconditionalAnnotationWhenTrue = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenTrue, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenTrue, FlowAnalysisAnnotations.MaybeNullWhenTrue, FlowAnalysisAnnotations.MaybeNull); } var unconditionalAnnotationWhenFalse = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenFalse, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenFalse, FlowAnalysisAnnotations.MaybeNullWhenFalse, FlowAnalysisAnnotations.MaybeNull); } // Convert Maybe/NotNullWhen into Maybe/NotNull or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotationCore(FlowAnalysisAnnotations annotations, FlowAnalysisAnnotations conditionalAnnotation, FlowAnalysisAnnotations replacementAnnotation) { if ((annotations & conditionalAnnotation) != 0) { return annotations | replacementAnnotation; } return annotations & ~replacementAnnotation; } } private static bool IsDefaultValue(BoundExpression expr) { switch (expr.Kind) { case BoundKind.Conversion: { var conversion = (BoundConversion)expr; var conversionKind = conversion.Conversion.Kind; return (conversionKind == ConversionKind.DefaultLiteral || conversionKind == ConversionKind.NullLiteral) && IsDefaultValue(conversion.Operand); } case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: return true; default: return false; } } private void ReportNullabilityMismatchInAssignment(SyntaxNode syntaxNode, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, syntaxNode, sourceType, destinationType); } private void ReportNullabilityMismatchInAssignment(Location location, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, location, sourceType, destinationType); } /// <summary> /// Update tracked value on assignment. /// </summary> private void TrackNullableStateForAssignment( BoundExpression? valueOpt, TypeWithAnnotations targetType, int targetSlot, TypeWithState valueType, int valueSlot = -1) { Debug.Assert(!IsConditionalState); if (this.State.Reachable) { if (!targetType.HasType) { return; } if (targetSlot <= 0 || targetSlot == valueSlot) { return; } if (!this.State.HasValue(targetSlot)) Normalize(ref this.State); var newState = valueType.State; SetStateAndTrackForFinally(ref this.State, targetSlot, newState); InheritDefaultState(targetType.Type, targetSlot); // https://github.com/dotnet/roslyn/issues/33428: Can the areEquivalentTypes check be removed // if InheritNullableStateOfMember asserts the member is valid for target and value? if (areEquivalentTypes(targetType, valueType)) { if (targetType.Type.IsReferenceType || targetType.TypeKind == TypeKind.TypeParameter || targetType.IsNullableType()) { if (valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot: targetSlot); } } else if (EmptyStructTypeCache.IsTrackableStructType(targetType.Type)) { InheritNullableStateOfTrackableStruct(targetType.Type, targetSlot, valueSlot, isDefaultValue: !(valueOpt is null) && IsDefaultValue(valueOpt), skipSlot: targetSlot); } } } static bool areEquivalentTypes(TypeWithAnnotations target, TypeWithState assignedValue) => target.Type.Equals(assignedValue.Type, TypeCompareKind.AllIgnoreOptions); } private void ReportNonSafetyDiagnostic(Location location) { ReportDiagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, location); } private void ReportDiagnostic(ErrorCode errorCode, SyntaxNode syntaxNode, params object[] arguments) { ReportDiagnostic(errorCode, syntaxNode.GetLocation(), arguments); } private void ReportDiagnostic(ErrorCode errorCode, Location location, params object[] arguments) { Debug.Assert(ErrorFacts.NullableWarnings.Contains(MessageProvider.Instance.GetIdForErrorCode((int)errorCode))); if (IsReachable() && !_disableDiagnostics) { Diagnostics.Add(errorCode, location, arguments); } } private void InheritNullableStateOfTrackableStruct(TypeSymbol targetType, int targetSlot, int valueSlot, bool isDefaultValue, int skipSlot = -1) { Debug.Assert(targetSlot > 0); Debug.Assert(EmptyStructTypeCache.IsTrackableStructType(targetType)); if (skipSlot < 0) { skipSlot = targetSlot; } if (!isDefaultValue && valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot); } else { foreach (var field in _emptyStructTypeCache.GetStructInstanceFields(targetType)) { InheritNullableStateOfMember(targetSlot, valueSlot, field, isDefaultValue: isDefaultValue, skipSlot); } } } private bool IsSlotMember(int slot, Symbol possibleMember) { TypeSymbol possibleBase = possibleMember.ContainingType; TypeSymbol possibleDerived = NominalSlotType(slot); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = _conversions.WithNullability(false); return conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo); } // 'skipSlot' is the original target slot that should be skipped in case of cycles. private void InheritNullableStateOfMember(int targetContainerSlot, int valueContainerSlot, Symbol member, bool isDefaultValue, int skipSlot) { Debug.Assert(targetContainerSlot > 0); Debug.Assert(skipSlot > 0); // Ensure member is valid for target and value. if (!IsSlotMember(targetContainerSlot, member)) return; TypeWithAnnotations fieldOrPropertyType = member.GetTypeOrReturnType(); if (fieldOrPropertyType.Type.IsReferenceType || fieldOrPropertyType.TypeKind == TypeKind.TypeParameter || fieldOrPropertyType.IsNullableType()) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { NullableFlowState value = isDefaultValue ? NullableFlowState.MaybeNull : fieldOrPropertyType.ToTypeWithState().State; int valueMemberSlot = -1; if (valueContainerSlot > 0) { valueMemberSlot = VariableSlot(member, valueContainerSlot); if (valueMemberSlot == skipSlot) { return; } value = this.State.HasValue(valueMemberSlot) ? this.State[valueMemberSlot] : NullableFlowState.NotNull; } SetStateAndTrackForFinally(ref this.State, targetMemberSlot, value); if (valueMemberSlot > 0) { InheritNullableStateOfTrackableType(targetMemberSlot, valueMemberSlot, skipSlot); } } } else if (EmptyStructTypeCache.IsTrackableStructType(fieldOrPropertyType.Type)) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { int valueMemberSlot = (valueContainerSlot > 0) ? GetOrCreateSlot(member, valueContainerSlot) : -1; if (valueMemberSlot == skipSlot) { return; } InheritNullableStateOfTrackableStruct(fieldOrPropertyType.Type, targetMemberSlot, valueMemberSlot, isDefaultValue: isDefaultValue, skipSlot); } } } private TypeSymbol NominalSlotType(int slot) { return _variables[slot].Symbol.GetTypeOrReturnType().Type; } /// <summary> /// Whenever assigning a variable, and that variable is not declared at the point the state is being set, /// and the new state is not <see cref="NullableFlowState.NotNull"/>, this method should be called to perform the /// state setting and to ensure the mutation is visible outside the finally block when the mutation occurs in a /// finally block. /// </summary> private void SetStateAndTrackForFinally(ref LocalState state, int slot, NullableFlowState newState) { state[slot] = newState; if (newState != NullableFlowState.NotNull && NonMonotonicState.HasValue) { var tryState = NonMonotonicState.Value; if (tryState.HasVariable(slot)) { tryState[slot] = newState.Join(tryState[slot]); NonMonotonicState = tryState; } } } protected override void JoinTryBlockState(ref LocalState self, ref LocalState other) { var tryState = other.GetStateForVariables(self.Id); Join(ref self, ref tryState); } private void InheritDefaultState(TypeSymbol targetType, int targetSlot) { Debug.Assert(targetSlot > 0); // Reset the state of any members of the target. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, targetSlot); foreach (var (variable, slot) in members) { var symbol = AsMemberOfType(targetType, variable.Symbol); SetStateAndTrackForFinally(ref this.State, slot, GetDefaultState(symbol)); InheritDefaultState(symbol.GetTypeOrReturnType().Type, slot); } members.Free(); } private NullableFlowState GetDefaultState(Symbol symbol) => ApplyUnconditionalAnnotations(symbol.GetTypeOrReturnType().ToTypeWithState(), GetRValueAnnotations(symbol)).State; private void InheritNullableStateOfTrackableType(int targetSlot, int valueSlot, int skipSlot) { Debug.Assert(targetSlot > 0); Debug.Assert(valueSlot > 0); // Clone the state for members that have been set on the value. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, valueSlot); foreach (var (variable, slot) in members) { var member = variable.Symbol; Debug.Assert(member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property || member.Kind == SymbolKind.Event); InheritNullableStateOfMember(targetSlot, valueSlot, member, isDefaultValue: false, skipSlot); } members.Free(); } protected override LocalState TopState() { var state = LocalState.ReachableState(_variables); state.PopulateAll(this); return state; } protected override LocalState UnreachableState() { return LocalState.UnreachableState(_variables); } protected override LocalState ReachableBottomState() { // Create a reachable state in which all variables are known to be non-null. return LocalState.ReachableState(_variables); } private void EnterParameters() { if (!(CurrentSymbol is MethodSymbol methodSymbol)) { return; } if (methodSymbol is SynthesizedRecordConstructor) { if (_hasInitialState) { // A record primary constructor's parameters are entered before analyzing initializers. // On the second pass, the correct parameter states (potentially modified by initializers) // are contained in the initial state. return; } } else if (methodSymbol.IsConstructor()) { if (!_hasInitialState) { // For most constructors, we only enter parameters after analyzing initializers. return; } } // The partial definition part may include optional parameters whose default values we want to simulate assigning at the beginning of the method methodSymbol = methodSymbol.PartialDefinitionPart ?? methodSymbol; var methodParameters = methodSymbol.Parameters; var signatureParameters = (_useDelegateInvokeParameterTypes ? _delegateInvokeMethod! : methodSymbol).Parameters; // save a state representing the possibility that parameter default values were not assigned to the parameters. var parameterDefaultsNotAssignedState = State.Clone(); for (int i = 0; i < methodParameters.Length; i++) { var parameter = methodParameters[i]; // In error scenarios, the method can potentially have more parameters than the signature. If so, use the parameter type for those // errored parameters var parameterType = i >= signatureParameters.Length ? parameter.TypeWithAnnotations : signatureParameters[i].TypeWithAnnotations; EnterParameter(parameter, parameterType); } Join(ref State, ref parameterDefaultsNotAssignedState); } private void EnterParameter(ParameterSymbol parameter, TypeWithAnnotations parameterType) { _variables.SetType(parameter, parameterType); if (parameter.RefKind != RefKind.Out) { int slot = GetOrCreateSlot(parameter); Debug.Assert(!IsConditionalState); if (slot > 0) { var state = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; this.State[slot] = state; if (EmptyStructTypeCache.IsTrackableStructType(parameterType.Type)) { InheritNullableStateOfTrackableStruct( parameterType.Type, slot, valueSlot: -1, isDefaultValue: parameter.ExplicitDefaultConstantValue?.IsNull == true); } } } } public override BoundNode? VisitParameterEqualsValue(BoundParameterEqualsValue equalsValue) { var parameter = equalsValue.Parameter; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterLValueType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); var resultType = VisitOptionalImplicitConversion( equalsValue.Value, parameterLValueType, useLegacyWarnings: false, trackMembers: false, assignmentKind: AssignmentKind.Assignment); Unsplit(); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, equalsValue.Value.Syntax.Location); return null; } internal static TypeWithState GetParameterState(TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) { if ((parameterAnnotations & FlowAnalysisAnnotations.AllowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.MaybeDefault); } if ((parameterAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.NotNull); } return parameterType.ToTypeWithState(); } public sealed override BoundNode? VisitReturnStatement(BoundReturnStatement node) { Debug.Assert(!IsConditionalState); var expr = node.ExpressionOpt; if (expr == null) { EnforceDoesNotReturn(node.Syntax); PendingBranches.Add(new PendingBranch(node, this.State, label: null)); SetUnreachable(); return null; } // Should not convert to method return type when inferring return type (when _returnTypesOpt != null). if (_returnTypesOpt == null && TryGetReturnType(out TypeWithAnnotations returnType, out FlowAnalysisAnnotations returnAnnotations)) { if (node.RefKind == RefKind.None && returnType.Type.SpecialType == SpecialType.System_Boolean) { // visit the expression without unsplitting, then check parameters marked with flow analysis attributes Visit(expr); } else { TypeWithState returnState; if (node.RefKind == RefKind.None) { returnState = VisitOptionalImplicitConversion(expr, returnType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); } else { // return ref expr; returnState = VisitRefExpression(expr, returnType); } // If the return has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(returnState, ToInwardAnnotations(returnAnnotations), node.Syntax.Location, boundValueOpt: expr); } } else { var result = VisitRvalueWithState(expr); if (_returnTypesOpt != null) { _returnTypesOpt.Add((node, result.ToTypeWithAnnotations(compilation))); } } EnforceDoesNotReturn(node.Syntax); if (IsConditionalState) { var joinedState = this.StateWhenTrue.Clone(); Join(ref joinedState, ref this.StateWhenFalse); PendingBranches.Add(new PendingBranch(node, joinedState, label: null, this.IsConditionalState, this.StateWhenTrue, this.StateWhenFalse)); } else { PendingBranches.Add(new PendingBranch(node, this.State, label: null)); } Unsplit(); if (CurrentSymbol is MethodSymbol method) { EnforceNotNullIfNotNull(node.Syntax, this.State, method.Parameters, method.ReturnNotNullIfParameterNotNull, ResultType.State, outputParam: null); } SetUnreachable(); return null; } private TypeWithState VisitRefExpression(BoundExpression expr, TypeWithAnnotations destinationType) { Visit(expr); TypeWithState resultType = ResultType; if (!expr.IsSuppressed && RemoveConversion(expr, includeExplicitConversions: false).expression.Kind != BoundKind.ThrowExpression) { var lvalueResultType = LvalueResultType; if (IsNullabilityMismatch(lvalueResultType, destinationType)) { // declared types must match ReportNullabilityMismatchInAssignment(expr.Syntax, lvalueResultType, destinationType); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(expr, destinationType, resultType, useLegacyWarnings: false); } } return resultType; } private bool TryGetReturnType(out TypeWithAnnotations type, out FlowAnalysisAnnotations annotations) { var method = CurrentSymbol as MethodSymbol; if (method is null) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } var delegateOrMethod = _useDelegateInvokeReturnType ? _delegateInvokeMethod! : method; var returnType = delegateOrMethod.ReturnTypeWithAnnotations; Debug.Assert((object)returnType != LambdaSymbol.ReturnTypeIsBeingInferred); if (returnType.IsVoidType()) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } if (!method.IsAsync) { annotations = method.ReturnTypeFlowAnalysisAnnotations; type = ApplyUnconditionalAnnotations(returnType, annotations); return true; } if (method.IsAsyncEffectivelyReturningGenericTask(compilation)) { type = ((NamedTypeSymbol)returnType.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); annotations = FlowAnalysisAnnotations.None; return true; } type = default; annotations = FlowAnalysisAnnotations.None; return false; } public override BoundNode? VisitLocal(BoundLocal node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); var type = GetDeclaredLocalResult(local); if (!node.Type.Equals(type.Type, TypeCompareKind.ConsiderEverything | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames)) { // When the local is used before or during initialization, there can potentially be a mismatch between node.LocalSymbol.Type and node.Type. We // need to prefer node.Type as we shouldn't be changing the type of the BoundLocal node during rewrite. // https://github.com/dotnet/roslyn/issues/34158 Debug.Assert(node.Type.IsErrorType() || type.Type.IsErrorType()); type = TypeWithAnnotations.Create(node.Type, type.NullableAnnotation); } SetResult(node, GetAdjustedResult(type.ToTypeWithState(), slot), type); SplitIfBooleanConstant(node); return null; } public override BoundNode? VisitBlock(BoundBlock node) { DeclareLocals(node.Locals); VisitStatementsWithLocalFunctions(node); return null; } private void VisitStatementsWithLocalFunctions(BoundBlock block) { // Since the nullable flow state affects type information, and types can be queried by // the semantic model, there needs to be a single flow state input to a local function // that cannot be path-dependent. To decide the local starting state we Meet the state // of captured variables from all the uses of the local function, computing the // conservative combination of all potential starting states. // // For performance we split the analysis into two phases: the first phase where we // analyze everything except the local functions, hoping to visit all of the uses of the // local function, and then a pass where we visit the local functions. If there's no // recursion or calls between the local functions, the starting state of the local // function should be stable and we don't need a second pass. if (!TrackingRegions && !block.LocalFunctions.IsDefaultOrEmpty) { // First visit everything else foreach (var stmt in block.Statements) { if (stmt.Kind != BoundKind.LocalFunctionStatement) { VisitStatement(stmt); } } // Now visit the local function bodies foreach (var stmt in block.Statements) { if (stmt is BoundLocalFunctionStatement localFunc) { VisitLocalFunctionStatement(localFunc); } } } else { foreach (var stmt in block.Statements) { VisitStatement(stmt); } } } public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { var localFunc = node.Symbol; var localFunctionState = GetOrCreateLocalFuncUsages(localFunc); // The starting state is the top state, but with captured // variables set according to Joining the state at all the // local function use sites var state = TopState(); var startingState = localFunctionState.StartingState; startingState.ForEach( (slot, variables) => { var symbol = variables[variables.RootSlot(slot)].Symbol; if (Symbol.IsCaptured(symbol, localFunc)) { state[slot] = startingState[slot]; } }, _variables); localFunctionState.Visited = true; AnalyzeLocalFunctionOrLambda( node, localFunc, state, delegateInvokeMethod: null, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false); SetInvalidResult(); return null; } private Variables GetOrCreateNestedFunctionVariables(Variables container, MethodSymbol lambdaOrLocalFunction) { _nestedFunctionVariables ??= PooledDictionary<MethodSymbol, Variables>.GetInstance(); if (!_nestedFunctionVariables.TryGetValue(lambdaOrLocalFunction, out var variables)) { variables = container.CreateNestedMethodScope(lambdaOrLocalFunction); _nestedFunctionVariables.Add(lambdaOrLocalFunction, variables); } Debug.Assert((object?)variables.Container == container); return variables; } private void AnalyzeLocalFunctionOrLambda( IBoundLambdaOrFunction lambdaOrFunction, MethodSymbol lambdaOrFunctionSymbol, LocalState state, MethodSymbol? delegateInvokeMethod, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethod is object); Debug.Assert(!useDelegateInvokeReturnType || delegateInvokeMethod is object); var oldSymbol = this._symbol; this._symbol = lambdaOrFunctionSymbol; var oldCurrentSymbol = this.CurrentSymbol; this.CurrentSymbol = lambdaOrFunctionSymbol; var oldDelegateInvokeMethod = _delegateInvokeMethod; _delegateInvokeMethod = delegateInvokeMethod; var oldUseDelegateInvokeParameterTypes = _useDelegateInvokeParameterTypes; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; var oldUseDelegateInvokeReturnType = _useDelegateInvokeReturnType; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; var oldReturnTypes = _returnTypesOpt; _returnTypesOpt = null; #if DEBUG var oldCompletingTargetTypedExpression = _completingTargetTypedExpression; _completingTargetTypedExpression = false; #endif var oldState = this.State; _variables = GetOrCreateNestedFunctionVariables(_variables, lambdaOrFunctionSymbol); this.State = state.CreateNestedMethodState(_variables); var previousSlot = _snapshotBuilderOpt?.EnterNewWalker(lambdaOrFunctionSymbol) ?? -1; try { var oldPending = SavePending(); EnterParameters(); var oldPending2 = SavePending(); // If this is an iterator, there's an implicit branch before the first statement // of the function where the enumerable is returned. if (lambdaOrFunctionSymbol.IsIterator) { PendingBranches.Add(new PendingBranch(null, this.State, null)); } VisitAlways(lambdaOrFunction.Body); EnforceDoesNotReturn(syntaxOpt: null); EnforceParameterNotNullOnExit(null, this.State); RestorePending(oldPending2); // process any forward branches within the lambda body ImmutableArray<PendingBranch> pendingReturns = RemoveReturns(); foreach (var pendingReturn in pendingReturns) { if (pendingReturn.Branch is BoundReturnStatement returnStatement) { EnforceParameterNotNullOnExit(returnStatement.Syntax, pendingReturn.State); EnforceNotNullWhenForPendingReturn(pendingReturn, returnStatement); } } RestorePending(oldPending); } finally { _snapshotBuilderOpt?.ExitWalker(this.SaveSharedState(), previousSlot); } _variables = _variables.Container!; this.State = oldState; #if DEBUG _completingTargetTypedExpression = oldCompletingTargetTypedExpression; #endif _returnTypesOpt = oldReturnTypes; _useDelegateInvokeReturnType = oldUseDelegateInvokeReturnType; _useDelegateInvokeParameterTypes = oldUseDelegateInvokeParameterTypes; _delegateInvokeMethod = oldDelegateInvokeMethod; this.CurrentSymbol = oldCurrentSymbol; this._symbol = oldSymbol; } protected override void VisitLocalFunctionUse( LocalFunctionSymbol symbol, LocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) { // Do not use this overload in NullableWalker. Use the overload below instead. throw ExceptionUtilities.Unreachable; } private void VisitLocalFunctionUse(LocalFunctionSymbol symbol) { Debug.Assert(!IsConditionalState); var localFunctionState = GetOrCreateLocalFuncUsages(symbol); var state = State.GetStateForVariables(localFunctionState.StartingState.Id); if (Join(ref localFunctionState.StartingState, ref state) && localFunctionState.Visited) { // If the starting state of the local function has changed and we've already visited // the local function, we need another pass stateChangedAfterUse = true; } } public override BoundNode? VisitDoStatement(BoundDoStatement node) { DeclareLocals(node.Locals); return base.VisitDoStatement(node); } public override BoundNode? VisitWhileStatement(BoundWhileStatement node) { DeclareLocals(node.Locals); return base.VisitWhileStatement(node); } public override BoundNode? VisitWithExpression(BoundWithExpression withExpr) { Debug.Assert(!IsConditionalState); var receiver = withExpr.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); var resultType = ResultType.ToTypeWithAnnotations(compilation); var resultState = ApplyUnconditionalAnnotations(resultType.ToTypeWithState(), GetRValueAnnotations(withExpr.CloneMethod)); var resultSlot = GetOrCreatePlaceholderSlot(withExpr); // carry over the null state of members of 'receiver' to the result of the with-expression. TrackNullableStateForAssignment(receiver, resultType, resultSlot, resultState, MakeSlot(receiver)); // use the declared nullability of Clone() for the top-level nullability of the result of the with-expression. SetResult(withExpr, resultState, resultType); VisitObjectCreationInitializer(resultSlot, resultType.Type, withExpr.InitializerExpression, delayCompletionForType: false); // Note: this does not account for the scenario where `Clone()` returns maybe-null and the with-expression has no initializers. // Tracking in https://github.com/dotnet/roslyn/issues/44759 return null; } public override BoundNode? VisitForStatement(BoundForStatement node) { DeclareLocals(node.OuterLocals); DeclareLocals(node.InnerLocals); return base.VisitForStatement(node); } public override BoundNode? VisitForEachStatement(BoundForEachStatement node) { DeclareLocals(node.IterationVariables); return base.VisitForEachStatement(node); } public override BoundNode? VisitUsingStatement(BoundUsingStatement node) { DeclareLocals(node.Locals); Visit(node.AwaitOpt); return base.VisitUsingStatement(node); } public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { Visit(node.AwaitOpt); return base.VisitUsingLocalDeclarations(node); } public override BoundNode? VisitFixedStatement(BoundFixedStatement node) { DeclareLocals(node.Locals); return base.VisitFixedStatement(node); } public override BoundNode? VisitConstructorMethodBody(BoundConstructorMethodBody node) { DeclareLocals(node.Locals); return base.VisitConstructorMethodBody(node); } private void DeclareLocal(LocalSymbol local) { if (local.DeclarationKind != LocalDeclarationKind.None) { int slot = GetOrCreateSlot(local); if (slot > 0) { this.State[slot] = GetDefaultState(ref this.State, slot); InheritDefaultState(GetDeclaredLocalResult(local).Type, slot); } } } private void DeclareLocals(ImmutableArray<LocalSymbol> locals) { foreach (var local in locals) { DeclareLocal(local); } } public override BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); // We need visit the optional arguments so that we can return nullability information // about them, but we don't want to communicate any information about anything underneath. // Additionally, tests like Scope_DeclaratorArguments_06 can have conditional expressions // in the optional arguments that can leave us in a split state, so we want to make sure // we are not in a conditional state after. Debug.Assert(!IsConditionalState); var oldDisable = _disableDiagnostics; _disableDiagnostics = true; var currentState = State; VisitAndUnsplitAll(node.ArgumentsOpt); _disableDiagnostics = oldDisable; SetState(currentState); if (node.DeclaredTypeOpt != null) { VisitTypeExpression(node.DeclaredTypeOpt); } var initializer = node.InitializerOpt; if (initializer is null) { return null; } TypeWithAnnotations type = local.TypeWithAnnotations; TypeWithState valueType; bool inferredType = node.InferredType; if (local.IsRef) { valueType = VisitRefExpression(initializer, type); } else { valueType = VisitOptionalImplicitConversion(initializer, targetTypeOpt: inferredType ? default : type, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); Unsplit(); } if (inferredType) { if (valueType.HasNullType) { Debug.Assert(type.Type.IsErrorType()); valueType = type.ToTypeWithState(); } type = valueType.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local, type); if (node.DeclaredTypeOpt != null) { SetAnalyzedNullability(node.DeclaredTypeOpt, new VisitResult(type.ToTypeWithState(), type), true); } } TrackNullableStateForAssignment(initializer, type, slot, valueType, MakeSlot(initializer)); return null; } protected override BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node) { Debug.Assert(!IsConditionalState); SetInvalidResult(); _ = base.VisitExpressionWithoutStackGuard(node); TypeWithState resultType = ResultType; #if DEBUG // Verify Visit method set _result. Debug.Assert((object?)resultType.Type != _invalidType.Type); Debug.Assert(AreCloseEnough(resultType.Type, node.Type)); #endif if (ShouldMakeNotNullRvalue(node)) { var result = resultType.WithNotNullState(); SetResult(node, result, LvalueResultType); } return null; } #if DEBUG // For asserts only. private static bool AreCloseEnough(TypeSymbol? typeA, TypeSymbol? typeB) { // https://github.com/dotnet/roslyn/issues/34993: We should be able to tighten this to ensure that we're actually always returning the same type, // not error if one is null or ignoring certain types if ((object?)typeA == typeB) { return true; } if (typeA is null || typeB is null) { return typeA?.IsErrorType() != false && typeB?.IsErrorType() != false; } return canIgnoreAnyType(typeA) || canIgnoreAnyType(typeB) || typeA.Equals(typeB, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); // Ignore TupleElementNames (see https://github.com/dotnet/roslyn/issues/23651). static bool canIgnoreAnyType(TypeSymbol type) { return type.VisitType((t, unused1, unused2) => canIgnoreType(t), (object?)null) is object; } static bool canIgnoreType(TypeSymbol type) { return type.IsErrorType() || type.IsDynamic() || type.HasUseSiteError || (type.IsAnonymousType && canIgnoreAnonymousType((NamedTypeSymbol)type)); } static bool canIgnoreAnonymousType(NamedTypeSymbol type) { return AnonymousTypeManager.GetAnonymousTypeFieldTypes(type).Any(static t => canIgnoreAnyType(t.Type)); } } private static bool AreCloseEnough(Symbol original, Symbol updated) { // When https://github.com/dotnet/roslyn/issues/38195 is fixed, this workaround needs to be removed if (original is ConstructedMethodSymbol || updated is ConstructedMethodSymbol) { return AreCloseEnough(original.OriginalDefinition, updated.OriginalDefinition); } return (original, updated) switch { (LambdaSymbol l, NamedTypeSymbol n) _ when n.IsDelegateType() => AreLambdaAndNewDelegateSimilar(l, n), (FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var oi } originalField, FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var ui } updatedField) => originalField.Type.Equals(updatedField.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) && oi == ui, _ => original.Equals(updated, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) }; } #endif private static bool AreLambdaAndNewDelegateSimilar(LambdaSymbol l, NamedTypeSymbol n) { var invokeMethod = n.DelegateInvokeMethod; return invokeMethod!.Parameters.SequenceEqual(l.Parameters, (p1, p2) => p1.Type.Equals(p2.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) && invokeMethod.ReturnType.Equals(l.ReturnType, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames); } public override BoundNode? Visit(BoundNode? node) { return Visit(node, expressionIsRead: true); } private BoundNode VisitLValue(BoundNode node) { return Visit(node, expressionIsRead: false); } private BoundNode Visit(BoundNode? node, bool expressionIsRead) { #if DEBUG Debug.Assert(!_completingTargetTypedExpression); #endif bool originalExpressionIsRead = _expressionIsRead; _expressionIsRead = expressionIsRead; TakeIncrementalSnapshot(node); var result = base.Visit(node); _expressionIsRead = originalExpressionIsRead; return result; } protected override void VisitStatement(BoundStatement statement) { SetInvalidResult(); base.VisitStatement(statement); SetInvalidResult(); } public override BoundNode? VisitObjectCreationExpression(BoundObjectCreationExpression node) { VisitObjectCreationExpressionBase(node); return null; } public override BoundNode? VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { // This method is only involved in method inference with unbound lambdas. // The diagnostics on arguments are reported by VisitObjectCreationExpression. SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); return null; } private void VisitObjectCreationExpressionBase(BoundObjectCreationExpressionBase node) { Debug.Assert(!IsConditionalState); bool isTargetTyped = node.WasTargetTyped; MethodSymbol? constructor = getConstructor(node, node.Type); var arguments = node.Arguments; (_, ImmutableArray<VisitArgumentResult> argumentResults, _, ArgumentsCompletionDelegate? argumentsCompletion) = VisitArguments( node, arguments, node.ArgumentRefKindsOpt, constructor?.Parameters ?? default, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, invokedAsExtensionMethod: false, constructor, delayCompletionForTargetMember: isTargetTyped); Debug.Assert(isTargetTyped == argumentsCompletion is not null); var type = node.Type; (int slot, NullableFlowState resultState, Func<TypeSymbol, MethodSymbol?, int>? initialStateInferenceCompletion) = inferInitialObjectState(node, type, constructor, arguments, argumentResults, isTargetTyped); Action<int, TypeSymbol>? initializerCompletion = null; var initializerOpt = node.InitializerExpressionOpt; if (initializerOpt != null) { initializerCompletion = VisitObjectCreationInitializer(slot, type, initializerOpt, delayCompletionForType: isTargetTyped); } TypeWithState result = setAnalyzedNullability(node, type, argumentResults, argumentsCompletion, initialStateInferenceCompletion, initializerCompletion, resultState, isTargetTyped); SetResultType(node, result, updateAnalyzedNullability: false); return; TypeWithState setAnalyzedNullability( BoundObjectCreationExpressionBase node, TypeSymbol? type, ImmutableArray<VisitArgumentResult> argumentResults, ArgumentsCompletionDelegate? argumentsCompletion, Func<TypeSymbol, MethodSymbol?, int>? initialStateInferenceCompletion, Action<int, TypeSymbol>? initializerCompletion, NullableFlowState resultState, bool isTargetTyped) { var result = TypeWithState.Create(type, resultState); if (isTargetTyped) { Debug.Assert(argumentsCompletion is not null); Debug.Assert(initialStateInferenceCompletion is not null); setAnalyzedNullabilityAsContinuation(node, argumentResults, argumentsCompletion, initialStateInferenceCompletion, initializerCompletion, resultState); } else { Debug.Assert(argumentsCompletion is null); Debug.Assert(initialStateInferenceCompletion is null); Debug.Assert(initializerCompletion is null); SetAnalyzedNullability(node, result); } return result; } void setAnalyzedNullabilityAsContinuation( BoundObjectCreationExpressionBase node, ImmutableArray<VisitArgumentResult> argumentResults, ArgumentsCompletionDelegate argumentsCompletion, Func<TypeSymbol, MethodSymbol?, int> initialStateInferenceCompletion, Action<int, TypeSymbol>? initializerCompletion, NullableFlowState resultState) { Debug.Assert(resultState == NullableFlowState.NotNull); TargetTypedAnalysisCompletion[node] = (TypeWithAnnotations resultTypeWithAnnotations) => { Debug.Assert(TypeSymbol.Equals(resultTypeWithAnnotations.Type, node.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); var arguments = node.Arguments; var type = resultTypeWithAnnotations.Type; MethodSymbol? constructor = getConstructor(node, type); argumentsCompletion(argumentResults, constructor?.Parameters ?? default, constructor); int slot = initialStateInferenceCompletion(type, constructor); initializerCompletion?.Invoke(slot, type); return setAnalyzedNullability( node, type, argumentResults, argumentsCompletion: null, initialStateInferenceCompletion: null, initializerCompletion: null, resultState, isTargetTyped: false); }; } static MethodSymbol? getConstructor(BoundObjectCreationExpressionBase node, TypeSymbol type) { var constructor = node.Constructor; if (constructor is not null && !type.IsInterfaceType()) { constructor = (MethodSymbol)AsMemberOfType(type, constructor); } return constructor; } (int slot, NullableFlowState resultState, Func<TypeSymbol, MethodSymbol?, int>? completion) inferInitialObjectState( BoundExpression node, TypeSymbol type, MethodSymbol? constructor, ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> argumentResults, bool isTargetTyped) { if (isTargetTyped) { return (-1, NullableFlowState.NotNull, inferInitialObjectStateAsContinuation(node, arguments, argumentResults)); } Debug.Assert(node.Kind is BoundKind.ObjectCreationExpression or BoundKind.DynamicObjectCreationExpression or BoundKind.NewT or BoundKind.NoPiaObjectCreationExpression); var argumentTypes = argumentResults.SelectAsArray(ar => ar.RValueType); int slot = -1; var resultState = NullableFlowState.NotNull; if (type is object) { slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { bool isDefaultValueTypeConstructor = constructor?.IsDefaultValueTypeConstructor() == true; if (EmptyStructTypeCache.IsTrackableStructType(type)) { var containingType = constructor?.ContainingType; if (containingType?.IsTupleType == true && !isDefaultValueTypeConstructor) { // new System.ValueTuple<T1, ..., TN>(e1, ..., eN) TrackNullableStateOfTupleElements(slot, containingType, arguments, argumentTypes, ((BoundObjectCreationExpression)node).ArgsToParamsOpt, useRestField: true); } else { InheritNullableStateOfTrackableStruct( type, slot, valueSlot: -1, isDefaultValue: isDefaultValueTypeConstructor); } } else if (type.IsNullableType()) { if (isDefaultValueTypeConstructor) { // a nullable value type created with its default constructor is by definition null resultState = NullableFlowState.MaybeNull; } else if (constructor?.ParameterCount == 1) { // if we deal with one-parameter ctor that takes underlying, then Value state is inferred from the argument. var parameterType = constructor.ParameterTypesWithAnnotations[0]; if (AreNullableAndUnderlyingTypes(type, parameterType.Type, out TypeWithAnnotations underlyingType)) { var operand = arguments[0]; int valueSlot = MakeSlot(operand); if (valueSlot > 0) { TrackNullableStateOfNullableValue(slot, type, operand, underlyingType.ToTypeWithState(), valueSlot); } } } } this.State[slot] = resultState; } } return (slot, resultState, null); } Func<TypeSymbol, MethodSymbol?, int> inferInitialObjectStateAsContinuation( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> argumentResults) { return (TypeSymbol type, MethodSymbol? constructor) => { var (slot, resultState, completion) = inferInitialObjectState(node, type, constructor, arguments, argumentResults, isTargetTyped: false); Debug.Assert(completion is null); Debug.Assert(resultState == NullableFlowState.NotNull); return slot; }; } } /// <summary> /// If <paramref name="delayCompletionForType"/>, <paramref name="containingSlot"/> is known only within returned delegate. /// </summary> /// <returns>A delegate to complete the initializer analysis.</returns> private Action<int, TypeSymbol>? VisitObjectCreationInitializer(int containingSlot, TypeSymbol containingType, BoundObjectInitializerExpressionBase node, bool delayCompletionForType) { Debug.Assert(!delayCompletionForType || containingSlot == -1); Action<int, TypeSymbol>? completion = null; TakeIncrementalSnapshot(node); switch (node) { case BoundObjectInitializerExpression objectInitializer: foreach (var initializer in objectInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.AssignmentOperator: completion += VisitObjectElementInitializer(containingSlot, containingType, (BoundAssignmentOperator)initializer, delayCompletionForType); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(objectInitializer.Placeholder); break; case BoundCollectionInitializerExpression collectionInitializer: foreach (var initializer in collectionInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.CollectionElementInitializer: completion += VisitCollectionElementInitializer((BoundCollectionElementInitializer)initializer, containingType, delayCompletionForType); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(collectionInitializer.Placeholder); break; default: ExceptionUtilities.UnexpectedValue(node.Kind); break; } return completion; } /// <summary> /// If <paramref name="delayCompletionForType"/>, <paramref name="containingSlot"/> is known only within returned delegate. /// </summary> /// <returns>A delegate to complete the element initializer analysis.</returns> private Action<int, TypeSymbol>? VisitObjectElementInitializer(int containingSlot, TypeSymbol containingType, BoundAssignmentOperator node, bool delayCompletionForType) { Debug.Assert(!delayCompletionForType || containingSlot == -1); TakeIncrementalSnapshot(node); var left = node.Left; switch (left.Kind) { case BoundKind.ObjectInitializerMember: { TakeIncrementalSnapshot(left); return visitMemberInitializer(containingSlot, containingType, node, delayCompletionForType); } default: VisitRvalue(node); return null; } Action<int, TypeSymbol>? visitMemberInitializer(int containingSlot, TypeSymbol containingType, BoundAssignmentOperator node, bool delayCompletionForType) { var objectInitializer = (BoundObjectInitializerMember)node.Left; Symbol? symbol = getTargetMember(containingType, objectInitializer); ImmutableArray<VisitArgumentResult> argumentResults = default; ArgumentsCompletionDelegate? argumentsCompletion = null; if (!objectInitializer.Arguments.IsDefaultOrEmpty) { // It is an error for an interpolated string to use the receiver of an object initializer indexer here, so we just use // a default visit result (_, argumentResults, _, argumentsCompletion) = VisitArguments( objectInitializer, objectInitializer.Arguments, objectInitializer.ArgumentRefKindsOpt, ((PropertySymbol?)symbol)?.Parameters ?? default, objectInitializer.ArgsToParamsOpt, objectInitializer.DefaultArguments, objectInitializer.Expanded, invokedAsExtensionMethod: false, method: null, delayCompletionForTargetMember: delayCompletionForType); } Action<int, Symbol>? initializationCompletion = null; if (symbol is object) { if (node.Right is BoundObjectInitializerExpressionBase initializer) { initializationCompletion = visitNestedInitializer(containingSlot, containingType, symbol, initializer, delayCompletionForType); } else { TakeIncrementalSnapshot(node.Right); initializationCompletion = visitMemberAssignment(node, containingSlot, symbol, delayCompletionForType); } // https://github.com/dotnet/roslyn/issues/35040: Should likely be setting _resultType in VisitObjectCreationInitializer // and using that value instead of reconstructing here } return setAnalyzedNullability(node, argumentResults, argumentsCompletion, initializationCompletion, delayCompletionForType); } Action<int, TypeSymbol>? setAnalyzedNullability( BoundAssignmentOperator node, ImmutableArray<VisitArgumentResult> argumentResults, ArgumentsCompletionDelegate? argumentsCompletion, Action<int, Symbol>? initializationCompletion, bool delayCompletionForType) { if (delayCompletionForType) { return setAnalyzedNullabilityAsContinuation(node, argumentResults, argumentsCompletion, initializationCompletion); } Debug.Assert(argumentsCompletion is null); Debug.Assert(initializationCompletion is null); var objectInitializer = (BoundObjectInitializerMember)node.Left; var result = new VisitResult(objectInitializer.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull); SetAnalyzedNullability(objectInitializer, result); SetAnalyzedNullability(node, result); return null; } Action<int, TypeSymbol>? setAnalyzedNullabilityAsContinuation( BoundAssignmentOperator node, ImmutableArray<VisitArgumentResult> argumentResults, ArgumentsCompletionDelegate? argumentsCompletion, Action<int, Symbol>? initializationCompletion) { return (int containingSlot, TypeSymbol containingType) => { Symbol? symbol = getTargetMember(containingType, (BoundObjectInitializerMember)node.Left); Debug.Assert(initializationCompletion is null || symbol is not null); argumentsCompletion?.Invoke(argumentResults, ((PropertySymbol?)symbol)?.Parameters ?? default, null); initializationCompletion?.Invoke(containingSlot, symbol!); var result = setAnalyzedNullability(node, argumentResults, argumentsCompletion: null, initializationCompletion: null, delayCompletionForType: false); Debug.Assert(result is null); }; } static Symbol? getTargetMember(TypeSymbol containingType, BoundObjectInitializerMember objectInitializer) { var symbol = objectInitializer.MemberSymbol; if (symbol != null) { Debug.Assert(TypeSymbol.Equals(objectInitializer.Type, symbol.GetTypeOrReturnType().Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); symbol = AsMemberOfType(containingType, symbol); } return symbol; } int getOrCreateSlot(int containingSlot, Symbol symbol) { return (containingSlot < 0 || !IsSlotMember(containingSlot, symbol)) ? -1 : GetOrCreateSlot(symbol, containingSlot); } Action<int, Symbol>? visitNestedInitializer(int containingSlot, TypeSymbol containingType, Symbol symbol, BoundObjectInitializerExpressionBase initializer, bool delayCompletionForType) { int slot = getOrCreateSlot(containingSlot, symbol); Debug.Assert(!delayCompletionForType || slot == -1); Action<int, TypeSymbol>? nestedCompletion = VisitObjectCreationInitializer(slot, symbol.GetTypeOrReturnType().Type, initializer, delayCompletionForType); return completeNestedInitializerAnalysis(symbol, initializer, slot, nestedCompletion, delayCompletionForType); } Action<int, Symbol>? completeNestedInitializerAnalysis( Symbol symbol, BoundObjectInitializerExpressionBase initializer, int slot, Action<int, TypeSymbol>? nestedCompletion, bool delayCompletionForType) { if (delayCompletionForType) { return completeNestedInitializerAnalysisAsContinuation(initializer, nestedCompletion); } Debug.Assert(nestedCompletion is null); if (slot >= 0 && !initializer.Initializers.IsEmpty) { if (!initializer.Type.IsValueType && State[slot].MayBeNull()) { ReportDiagnostic(ErrorCode.WRN_NullReferenceInitializer, initializer.Syntax, symbol); } } return null; } Action<int, Symbol>? completeNestedInitializerAnalysisAsContinuation(BoundObjectInitializerExpressionBase initializer, Action<int, TypeSymbol>? nestedCompletion) { return (int containingSlot, Symbol symbol) => { int slot = getOrCreateSlot(containingSlot, symbol); completeNestedInitializerAnalysis(symbol, initializer, slot, nestedCompletion: null, delayCompletionForType: false); nestedCompletion?.Invoke(slot, symbol.GetTypeOrReturnType().Type); }; } Action<int, Symbol>? visitMemberAssignment(BoundAssignmentOperator node, int containingSlot, Symbol symbol, bool delayCompletionForType, Func<TypeWithAnnotations, TypeWithState>? conversionCompletion = null) { Debug.Assert(!delayCompletionForType || conversionCompletion is null); if (!delayCompletionForType && conversionCompletion is null) { TakeIncrementalSnapshot(node.Right); } Debug.Assert(symbol.GetTypeOrReturnType().HasType); var type = ApplyLValueAnnotations(symbol.GetTypeOrReturnType(), GetObjectInitializerMemberLValueAnnotations(symbol)); (TypeWithState resultType, conversionCompletion) = conversionCompletion is not null ? (conversionCompletion(type), null) : VisitOptionalImplicitConversion(node.Right, type, useLegacyWarnings: false, trackMembers: true, AssignmentKind.Assignment, delayCompletionForType); Unsplit(); if (delayCompletionForType) { Debug.Assert(conversionCompletion is not null); return visitMemberAssignmentAsContinuation(node, conversionCompletion); } Debug.Assert(conversionCompletion is null); int slot = getOrCreateSlot(containingSlot, symbol); TrackNullableStateForAssignment(node.Right, type, slot, resultType, MakeSlot(node.Right)); return null; } Action<int, Symbol>? visitMemberAssignmentAsContinuation(BoundAssignmentOperator node, Func<TypeWithAnnotations, TypeWithState> conversionCompletion) { return (int containingSlot, Symbol symbol) => { var result = visitMemberAssignment(node, containingSlot, symbol, delayCompletionForType: false, conversionCompletion); Debug.Assert(result is null); }; } } [Obsolete("Use VisitCollectionElementInitializer(BoundCollectionElementInitializer node, TypeSymbol containingType, bool delayCompletionForType) instead.", true)] #pragma warning disable IDE0051 // Remove unused private members private new void VisitCollectionElementInitializer(BoundCollectionElementInitializer node) #pragma warning restore IDE0051 // Remove unused private members { throw ExceptionUtilities.Unreachable; } private Action<int, TypeSymbol>? VisitCollectionElementInitializer(BoundCollectionElementInitializer node, TypeSymbol containingType, bool delayCompletionForType) { ImmutableArray<VisitArgumentResult> argumentResults = default; MethodSymbol addMethod = addMethodAsMemberOfContainingType(node, containingType, ref argumentResults); // Note: we analyze even omitted calls (MethodSymbol? reinferredMethod, argumentResults, _, ArgumentsCompletionDelegate? visitArgumentsCompletion) = VisitArguments( node, node.Arguments, refKindsOpt: default, addMethod.Parameters, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod, addMethod, delayCompletionForTargetMember: delayCompletionForType); #if DEBUG if (node.InvokedAsExtensionMethod) { VisitArgumentResult receiverResult = argumentResults[0]; Debug.Assert(TypeSymbol.Equals(containingType, receiverResult.VisitResult.RValueType.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); Debug.Assert(TypeSymbol.Equals(containingType, receiverResult.LValueType.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); } #endif return setUpdatedSymbol(node, containingType, reinferredMethod, argumentResults, visitArgumentsCompletion, delayCompletionForType); Action<int, TypeSymbol>? setUpdatedSymbol( BoundCollectionElementInitializer node, TypeSymbol containingType, MethodSymbol? reinferredMethod, ImmutableArray<VisitArgumentResult> argumentResults, ArgumentsCompletionDelegate? visitArgumentsCompletion, bool delayCompletionForType) { if (delayCompletionForType) { Debug.Assert(visitArgumentsCompletion is not null); return setUpdatedSymbolAsContinuation(node, argumentResults, visitArgumentsCompletion); } Debug.Assert(visitArgumentsCompletion is null); Debug.Assert(reinferredMethod is object); if (node.ImplicitReceiverOpt != null) { Debug.Assert(node.ImplicitReceiverOpt.Kind == BoundKind.ObjectOrCollectionValuePlaceholder); SetAnalyzedNullability(node.ImplicitReceiverOpt, new VisitResult(node.ImplicitReceiverOpt.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull)); } SetUnknownResultNullability(node); SetUpdatedSymbol(node, node.AddMethod, reinferredMethod); return null; } Action<int, TypeSymbol>? setUpdatedSymbolAsContinuation( BoundCollectionElementInitializer node, ImmutableArray<VisitArgumentResult> argumentResults, ArgumentsCompletionDelegate visitArgumentsCompletion) { return (int containingSlot, TypeSymbol containingType) => { MethodSymbol addMethod = addMethodAsMemberOfContainingType(node, containingType, ref argumentResults); setUpdatedSymbol( node, containingType, visitArgumentsCompletion.Invoke(argumentResults, addMethod.Parameters, addMethod).method, argumentResults, visitArgumentsCompletion: null, delayCompletionForType: false); }; } static MethodSymbol addMethodAsMemberOfContainingType(BoundCollectionElementInitializer node, TypeSymbol containingType, ref ImmutableArray<VisitArgumentResult> argumentResults) { var method = node.AddMethod; if (node.InvokedAsExtensionMethod) { if (!argumentResults.IsDefault) { VisitArgumentResult receiverResult = argumentResults[0]; Debug.Assert(TypeSymbol.Equals(containingType, receiverResult.VisitResult.RValueType.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); Debug.Assert(TypeSymbol.Equals(containingType, receiverResult.LValueType.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); var builder = ArrayBuilder<VisitArgumentResult>.GetInstance(argumentResults.Length); builder.Add( new VisitArgumentResult( new VisitResult( TypeWithState.Create(containingType, receiverResult.RValueType.State), receiverResult.LValueType.WithType(containingType)), receiverResult.StateForLambda)); builder.AddRange(argumentResults, 1, argumentResults.Length - 1); argumentResults = builder.ToImmutableAndFree(); } } else { method = (MethodSymbol)AsMemberOfType(containingType, method); } return method; } } private void SetNotNullResult(BoundExpression node) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); } /// <summary> /// Returns true if the type is a struct with no fields or properties. /// </summary> protected override bool IsEmptyStructType(TypeSymbol type) { if (type.TypeKind != TypeKind.Struct) { return false; } // EmptyStructTypeCache.IsEmptyStructType() returns false // if there are non-cyclic fields. if (!_emptyStructTypeCache.IsEmptyStructType(type)) { return false; } if (type.SpecialType != SpecialType.None) { return true; } var members = ((NamedTypeSymbol)type).GetMembersUnordered(); // EmptyStructTypeCache.IsEmptyStructType() returned true. If there are fields, // at least one of those fields must be cyclic, so treat the type as empty. if (members.Any(static m => m.Kind == SymbolKind.Field)) { return true; } // If there are properties, the type is not empty. if (members.Any(static m => m.Kind == SymbolKind.Property)) { return false; } return true; } private int GetOrCreatePlaceholderSlot(BoundExpression node) { Debug.Assert(node.Type is object); if (IsEmptyStructType(node.Type)) { return -1; } return GetOrCreatePlaceholderSlot(node, TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated)); } private int GetOrCreatePlaceholderSlot(object identifier, TypeWithAnnotations type) { _placeholderLocalsOpt ??= PooledDictionary<object, PlaceholderLocal>.GetInstance(); if (!_placeholderLocalsOpt.TryGetValue(identifier, out var placeholder)) { placeholder = new PlaceholderLocal(CurrentSymbol, identifier, type); _placeholderLocalsOpt.Add(identifier, placeholder); } Debug.Assert((object)placeholder != null); return GetOrCreateSlot(placeholder, forceSlotEvenIfEmpty: true); } public override BoundNode? VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { Debug.Assert(!IsConditionalState); Debug.Assert(node.Type.IsAnonymousType); var anonymousType = (NamedTypeSymbol)node.Type; var arguments = node.Arguments; var argumentTypes = arguments.SelectAsArray((arg, self) => self.VisitRvalueWithState(arg), this); var argumentsWithAnnotations = argumentTypes.SelectAsArray(arg => arg.ToTypeWithAnnotations(compilation)); if (argumentsWithAnnotations.All(argType => argType.HasType)) { anonymousType = AnonymousTypeManager.ConstructAnonymousTypeSymbol(anonymousType, argumentsWithAnnotations); int receiverSlot = GetOrCreatePlaceholderSlot(node); int currentDeclarationIndex = 0; for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var argumentType = argumentTypes[i]; var property = AnonymousTypeManager.GetAnonymousTypeProperty(anonymousType, i); if (property.Type.SpecialType != SpecialType.System_Void) { // A void element results in an error type in the anonymous type but not in the property's container! // To avoid failing an assertion later, we skip them. var slot = GetOrCreateSlot(property, receiverSlot); TrackNullableStateForAssignment(argument, property.TypeWithAnnotations, slot, argumentType, MakeSlot(argument)); var currentDeclaration = getDeclaration(node, property, ref currentDeclarationIndex); if (currentDeclaration is object) { TakeIncrementalSnapshot(currentDeclaration); SetAnalyzedNullability(currentDeclaration, new VisitResult(argumentType, property.TypeWithAnnotations)); } } } } SetResultType(node, TypeWithState.Create(anonymousType, NullableFlowState.NotNull)); return null; static BoundAnonymousPropertyDeclaration? getDeclaration(BoundAnonymousObjectCreationExpression node, PropertySymbol currentProperty, ref int currentDeclarationIndex) { if (currentDeclarationIndex >= node.Declarations.Length) { return null; } var currentDeclaration = node.Declarations[currentDeclarationIndex]; if (currentDeclaration.Property.MemberIndexOpt == currentProperty.MemberIndexOpt) { currentDeclarationIndex++; return currentDeclaration; } return null; } } public override BoundNode? VisitArrayCreation(BoundArrayCreation node) { foreach (var expr in node.Bounds) { VisitRvalue(expr); } var initialization = node.InitializerOpt; if (initialization is null) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return null; } var arrayType = VisitArrayInitialization(node.Type, initialization, node.HasErrors); SetResultType(node, TypeWithState.Create(arrayType, NullableFlowState.NotNull)); return null; } private TypeSymbol VisitArrayInitialization(TypeSymbol type, BoundArrayInitialization initialization, bool hasErrors) { TakeIncrementalSnapshot(initialization); var expressions = ArrayBuilder<BoundExpression>.GetInstance(initialization.Initializers.Length); GetArrayElements(initialization, expressions); int n = expressions.Count; // Consider recording in the BoundArrayCreation // whether the array was implicitly typed, rather than relying on syntax. var elementType = type switch { ArrayTypeSymbol arrayType => arrayType.ElementTypeWithAnnotations, PointerTypeSymbol pointerType => pointerType.PointedAtTypeWithAnnotations, NamedTypeSymbol spanType => getSpanElementType(spanType), _ => throw ExceptionUtilities.UnexpectedValue(type.TypeKind) }; var resultType = type; if (!initialization.IsInferred) { foreach (var expr in expressions) { _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment); Unsplit(); } } else { var expressionsNoConversions = ArrayBuilder<BoundExpression>.GetInstance(n); var conversions = ArrayBuilder<Conversion>.GetInstance(n); var expressionTypes = ArrayBuilder<TypeWithState>.GetInstance(n); var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); foreach (var expression in expressions) { // collect expressions, conversions and result types (BoundExpression expressionNoConversion, Conversion conversion) = RemoveConversion(expression, includeExplicitConversions: false); expressionsNoConversions.Add(expressionNoConversion); conversions.Add(conversion); SnapshotWalkerThroughConversionGroup(expression, expressionNoConversion); var expressionType = VisitRvalueWithState(expressionNoConversion); expressionTypes.Add(expressionType); if (!IsTargetTypedExpression(expressionNoConversion)) { placeholderBuilder.Add(CreatePlaceholderIfNecessary(expressionNoConversion, expressionType.ToTypeWithAnnotations(compilation))); } } var placeholders = placeholderBuilder.ToImmutableAndFree(); TypeSymbol? bestType = null; if (!hasErrors) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bestType = BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo, out _); } TypeWithAnnotations inferredType = (bestType is null) ? elementType.SetUnknownNullabilityForReferenceTypes() : TypeWithAnnotations.Create(bestType); if (bestType is object) { // Convert elements to best type to determine element top-level nullability and to report nested nullability warnings for (int i = 0; i < n; i++) { var expressionNoConversion = expressionsNoConversions[i]; var expression = GetConversionIfApplicable(expressions[i], expressionNoConversion); expressionTypes[i] = VisitConversion(expression, expressionNoConversion, conversions[i], inferredType, expressionTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: true, reportTopLevelWarnings: false); } // Set top-level nullability on inferred element type var elementState = BestTypeInferrer.GetNullableState(expressionTypes); inferredType = TypeWithState.Create(inferredType.Type, elementState).ToTypeWithAnnotations(compilation); for (int i = 0; i < n; i++) { // Report top-level warnings _ = VisitConversion(conversionOpt: null, conversionOperand: expressionsNoConversions[i], Conversion.Identity, targetTypeWithNullability: inferredType, operandType: expressionTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: false); } } else { // We need to ensure that we're tracking the inferred type with nullability of any conversions that // were stripped off. for (int i = 0; i < n; i++) { TrackAnalyzedNullabilityThroughConversionGroup(inferredType.ToTypeWithState(), expressions[i] as BoundConversion, expressionsNoConversions[i]); } } expressionsNoConversions.Free(); conversions.Free(); expressionTypes.Free(); resultType = type switch { ArrayTypeSymbol arrayType => arrayType.WithElementType(inferredType), PointerTypeSymbol pointerType => pointerType.WithPointedAtType(inferredType), NamedTypeSymbol spanType => setSpanElementType(spanType, inferredType), _ => throw ExceptionUtilities.UnexpectedValue(type.TypeKind) }; } expressions.Free(); return resultType; static TypeWithAnnotations getSpanElementType(NamedTypeSymbol namedType) { Debug.Assert(namedType.Name == "Span"); Debug.Assert(namedType.OriginalDefinition.Arity == 1); return namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; } static TypeSymbol setSpanElementType(NamedTypeSymbol namedType, TypeWithAnnotations elementType) { Debug.Assert(namedType.Name == "Span"); Debug.Assert(namedType.OriginalDefinition.Arity == 1); return namedType.OriginalDefinition.Construct(ImmutableArray.Create(elementType)); } } private static bool IsTargetTypedExpression(BoundExpression node) { return node is BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true } or BoundObjectCreationExpressionBase { WasTargetTyped: true } or BoundDelegateCreationExpression { WasTargetTyped: true }; } /// <summary> /// Applies analysis similar to <see cref="VisitArrayCreation"/>. /// The expressions returned from a lambda are not converted though, so we'll have to classify fresh conversions. /// Note: even if some conversions fail, we'll proceed to infer top-level nullability. That is reasonable in common cases. /// </summary> internal static TypeWithAnnotations BestTypeForLambdaReturns( ArrayBuilder<(BoundExpression expr, TypeWithAnnotations resultType, bool isChecked)> returns, Binder binder, BoundNode node, Conversions conversions, out bool inferredFromFunctionType) { var walker = new NullableWalker(binder.Compilation, symbol: null, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, conversions: conversions, variables: null, baseOrThisInitializer: null, returnTypesOpt: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); int n = returns.Count; var resultTypes = ArrayBuilder<TypeWithAnnotations>.GetInstance(n); var placeholdersBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var (returnExpr, resultType, _) = returns[i]; resultTypes.Add(resultType); placeholdersBuilder.Add(CreatePlaceholderIfNecessary(returnExpr, resultType)); } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var placeholders = placeholdersBuilder.ToImmutableAndFree(); TypeSymbol? bestType = BestTypeInferrer.InferBestType(placeholders, walker._conversions, ref discardedUseSiteInfo, out inferredFromFunctionType); TypeWithAnnotations inferredType; if (bestType is { }) { // Note: so long as we have a best type, we can proceed. var bestTypeWithObliviousAnnotation = TypeWithAnnotations.Create(bestType); Conversions conversionsWithoutNullability = walker._conversions.WithNullability(false); for (int i = 0; i < n; i++) { BoundExpression placeholder = placeholders[i]; Conversion conversion = conversionsWithoutNullability.ClassifyConversionFromExpression(placeholder, bestType, isChecked: returns[i].isChecked, ref discardedUseSiteInfo); resultTypes[i] = walker.VisitConversion(conversionOpt: null, placeholder, conversion, bestTypeWithObliviousAnnotation, resultTypes[i].ToTypeWithState(), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Return, reportRemainingWarnings: false, reportTopLevelWarnings: false).ToTypeWithAnnotations(binder.Compilation); } // Set top-level nullability on inferred type inferredType = TypeWithAnnotations.Create(bestType, BestTypeInferrer.GetNullableAnnotation(resultTypes)); } else { inferredType = default; } resultTypes.Free(); walker.Free(); return inferredType; } private static void GetArrayElements(BoundArrayInitialization node, ArrayBuilder<BoundExpression> builder) { foreach (var child in node.Initializers) { if (child.Kind == BoundKind.ArrayInitialization) { GetArrayElements((BoundArrayInitialization)child, builder); } else { builder.Add(child); } } } public override BoundNode? VisitArrayAccess(BoundArrayAccess node) { Debug.Assert(!IsConditionalState); Visit(node.Expression); Debug.Assert(!IsConditionalState); Debug.Assert(!node.Expression.Type!.IsValueType); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(node.Expression); var type = ResultType.Type as ArrayTypeSymbol; foreach (var i in node.Indices) { VisitRvalue(i); } TypeWithAnnotations result; if (node.Indices.Length == 1 && TypeSymbol.Equals(node.Indices[0].Type, compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything2)) { result = TypeWithAnnotations.Create(type); } else { result = type?.ElementTypeWithAnnotations ?? default; } SetLvalueResultType(node, result); return null; } private TypeWithState InferResultNullability(BinaryOperatorKind operatorKind, MethodSymbol? methodOpt, TypeSymbol resultType, TypeWithState leftType, TypeWithState rightType) { NullableFlowState resultState = NullableFlowState.NotNull; if (operatorKind.IsUserDefined()) { if (methodOpt?.ParameterCount == 2) { if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { return GetLiftedReturnType(methodOpt.ReturnTypeWithAnnotations, leftType.State.Join(rightType.State)); } var resultTypeWithState = GetReturnTypeWithState(methodOpt); if ((leftType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[0].Name)) || (rightType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[1].Name))) { resultTypeWithState = resultTypeWithState.WithNotNullState(); } return resultTypeWithState; } } else if (!operatorKind.IsDynamic() && !resultType.IsValueType) { switch (operatorKind.Operator() | operatorKind.OperandTypes()) { case BinaryOperatorKind.DelegateCombination: resultState = leftType.State.Meet(rightType.State); break; case BinaryOperatorKind.DelegateRemoval: resultState = NullableFlowState.MaybeNull; // Delegate removal can produce null. break; default: resultState = NullableFlowState.NotNull; break; } } if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { resultState = leftType.State.Join(rightType.State); } return TypeWithState.Create(resultType, resultState); } protected override void VisitBinaryOperatorChildren(ArrayBuilder<BoundBinaryOperator> stack) { var binary = stack.Pop(); var (leftOperand, leftConversion) = RemoveConversion(binary.Left, includeExplicitConversions: false); // Only the leftmost operator of a left-associative binary operator chain can learn from a conditional access on the left // For simplicity, we just special case it here. // For example, `a?.b(out x) == true` has a conditional access on the left of the operator, // but `expr == a?.b(out x) == true` has a conditional access on the right of the operator if (VisitPossibleConditionalAccess(leftOperand, out var conditionalStateWhenNotNull) && CanPropagateStateWhenNotNull(leftConversion) && binary.OperatorKind.Operator() is BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // Consider the following two scenarios: // `a?.b(x = new object()) == c.d(x = null)` // `x` is maybe-null after expression // `a?.b(x = null) == c.d(x = new object())` // `x` is not-null after expression // In this scenario, we visit the RHS twice: // (1) Once using the single "stateWhenNotNull" after the LHS, in order to update the "stateWhenNotNull" with the effects of the RHS // (2) Once using the "worst case" state after the LHS for diagnostics and public API // After the two visits of the RHS, we may set a conditional state using the state after (1) as the StateWhenTrue and the state after (2) as the StateWhenFalse. // Depending on whether `==` or `!=` was used, and depending on the value of the RHS, we may then swap the StateWhenTrue with the StateWhenFalse. var oldDisableDiagnostics = _disableDiagnostics; _disableDiagnostics = true; var stateAfterLeft = this.State; SetState(getUnconditionalStateWhenNotNull(rightOperand, conditionalStateWhenNotNull)); VisitRvalue(rightOperand); var stateWhenNotNull = this.State; _disableDiagnostics = oldDisableDiagnostics; // Now visit the right side for public API and diagnostics using the worst-case state from the LHS. // Note that we do this visit last to try and make sure that the "visit for public API" overwrites walker state recorded during previous visits where possible. SetState(stateAfterLeft); var rightType = VisitRvalueWithState(rightOperand); ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); if (isKnownNullOrNotNull(rightOperand, rightType)) { var isNullConstant = rightOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); } if (stack.Count == 0) { return; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } while (true) { if (!learnFromConditionalAccessOrBoolConstant()) { Unsplit(); // VisitRvalue does this UseRvalueOnly(leftOperand); // drop lvalue part AfterLeftChildHasBeenVisited(leftOperand, leftConversion, binary); } if (stack.Count == 0) { break; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } static bool isEquals(BoundBinaryOperator binary) => binary.OperatorKind.Operator() == BinaryOperatorKind.Equal; static bool isKnownNullOrNotNull(BoundExpression expr, TypeWithState resultType) { return resultType.State.IsNotNull() || expr.ConstantValue is object; } LocalState getUnconditionalStateWhenNotNull(BoundExpression otherOperand, PossiblyConditionalState conditionalStateWhenNotNull) { LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else if (isEquals(binary) && otherOperand.ConstantValue is { IsBoolean: true, BooleanValue: var boolValue }) { // can preserve conditional state from `.TryGetValue` in `dict?.TryGetValue(key, out value) == true`, // but not in `dict?.TryGetValue(key, out value) != false` stateWhenNotNull = boolValue ? conditionalStateWhenNotNull.StateWhenTrue : conditionalStateWhenNotNull.StateWhenFalse; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } return stateWhenNotNull; } // Returns true if `binary.Right` was visited by the call. bool learnFromConditionalAccessOrBoolConstant() { if (binary.OperatorKind.Operator() is not (BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual)) { return false; } var leftResult = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // `true == a?.b(out x)` if (isKnownNullOrNotNull(leftOperand, leftResult) && CanPropagateStateWhenNotNull(rightConversion) && TryVisitConditionalAccess(rightOperand, out var conditionalStateWhenNotNull)) { ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftResult, rightOperand, rightConversion, rightType: ResultType, binary); var stateWhenNotNull = getUnconditionalStateWhenNotNull(leftOperand, conditionalStateWhenNotNull); var isNullConstant = leftOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); return true; } // can only learn from a bool constant operand here if it's using the built in `bool operator ==(bool left, bool right)` if (binary.OperatorKind.IsUserDefined()) { return false; } // `(x != null) == true` if (IsConditionalState && binary.Right.ConstantValue is { IsBoolean: true } rightConstant) { var (stateWhenTrue, stateWhenFalse) = (StateWhenTrue.Clone(), StateWhenFalse.Clone()); Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); // record result for the right SetConditionalState(isEquals(binary) == rightConstant.BooleanValue ? (stateWhenTrue, stateWhenFalse) : (stateWhenFalse, stateWhenTrue)); } // `true == (x != null)` else if (binary.Left.ConstantValue is { IsBoolean: true } leftConstant) { Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); if (IsConditionalState && isEquals(binary) != leftConstant.BooleanValue) { SetConditionalState(StateWhenFalse, StateWhenTrue); } } else { return false; } // record result for the binary Debug.Assert(binary.Type.SpecialType == SpecialType.System_Boolean); SetResult(binary, TypeWithState.ForType(binary.Type), TypeWithAnnotations.Create(binary.Type)); return true; } } private void ReinferBinaryOperatorAndSetResult( BoundExpression leftOperand, Conversion leftConversion, TypeWithState leftType, BoundExpression rightOperand, Conversion rightConversion, TypeWithState rightType, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); // At this point, State.Reachable may be false for // invalid code such as `s + throw new Exception()`. var method = binary.Method; if (binary.OperatorKind.IsUserDefined() && method?.ParameterCount == 2) { // Update method based on inferred operand type. TypeSymbol methodContainer = method.ContainingType; bool isLifted = binary.OperatorKind.IsLifted(); TypeWithState leftUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, leftType); TypeWithState rightUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, rightType); TypeSymbol asMemberOfType = getTypeIfContainingType(methodContainer, leftUnderlyingType.Type, leftOperand) ?? getTypeIfContainingType(methodContainer, rightUnderlyingType.Type, rightOperand) ?? methodContainer; method = (MethodSymbol)AsMemberOfType(asMemberOfType, method); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameters = method.Parameters; visitOperandConversionAndPostConditions(binary.Left, leftOperand, leftConversion, parameters[0], leftUnderlyingType); visitOperandConversionAndPostConditions(binary.Right, rightOperand, rightConversion, parameters[1], rightUnderlyingType); SetUpdatedSymbol(binary, binary.Method!, method); void visitOperandConversionAndPostConditions( BoundExpression expr, BoundExpression operand, Conversion conversion, ParameterSymbol parameter, TypeWithState operandType) { var parameterAnnotations = GetParameterAnnotations(parameter); var targetTypeWithNullability = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); if (isLifted && targetTypeWithNullability.Type.IsNonNullableValueType()) { targetTypeWithNullability = TypeWithAnnotations.Create(MakeNullableOf(targetTypeWithNullability)); } var resultType = VisitConversion( expr as BoundConversion, operand, conversion, targetTypeWithNullability, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument, parameter); CheckDisallowedNullAssignment(resultType, parameterAnnotations, expr.Syntax.Location, operand); LearnFromPostConditions(operand, parameterAnnotations); } } else { // Assume this is a built-in operator in which case the parameter types are unannotated. visitOperandConversion(binary.Left, leftOperand, leftConversion, leftType); visitOperandConversion(binary.Right, rightOperand, rightConversion, rightType); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, TypeWithState operandType) { if (expr.Type is null) { Debug.Assert(operand == expr); } else { _ = VisitConversion( expr as BoundConversion, operand, conversion, TypeWithAnnotations.Create(expr.Type), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument); } } } Debug.Assert(!IsConditionalState); if (binary.OperatorKind.IsLifted() && binary.OperatorKind.Operator() is BinaryOperatorKind.GreaterThan or BinaryOperatorKind.GreaterThanOrEqual or BinaryOperatorKind.LessThan or BinaryOperatorKind.LessThanOrEqual) { Debug.Assert(binary.Type.SpecialType == SpecialType.System_Boolean); SplitAndLearnFromNonNullTest(binary.Left, whenTrue: true); SplitAndLearnFromNonNullTest(binary.Right, whenTrue: true); } // For nested binary operators, this can be the only time they're visited due to explicit stack used in AbstractFlowPass.VisitBinaryOperator, // so we need to set the flow-analyzed type here. var inferredResult = InferResultNullability(binary.OperatorKind, method, binary.Type, leftType, rightType); SetResult(binary, inferredResult, inferredResult.ToTypeWithAnnotations(compilation)); return; TypeSymbol? getTypeIfContainingType(TypeSymbol baseType, TypeSymbol? derivedType, BoundExpression operand) { if (derivedType is null || IsTargetTypedExpression(operand)) { return null; } derivedType = derivedType.StrippedType(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyBuiltInConversion(derivedType, baseType, isChecked: false, ref discardedUseSiteInfo); if (conversion.Exists && !conversion.IsExplicit) { return derivedType; } return null; } } private void AfterLeftChildHasBeenVisited( BoundExpression leftOperand, Conversion leftConversion, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); VisitRvalue(rightOperand); var rightType = ResultType; ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); BinaryOperatorKind op = binary.OperatorKind.Operator(); if (op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) { // learn from null constant BoundExpression? operandComparedToNull = null; if (binary.Right.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Left; } else if (binary.Left.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Right; } if (operandComparedToNull != null) { // Set all nested conditional slots. For example in a?.b?.c we'll set a, b, and c. bool nonNullCase = op != BinaryOperatorKind.Equal; // true represents WhenTrue SplitAndLearnFromNonNullTest(operandComparedToNull, whenTrue: nonNullCase); // `x == null` and `x != null` are pure null tests so update the null-state in the alternative branch too LearnFromNullTest(operandComparedToNull, ref nonNullCase ? ref StateWhenFalse : ref StateWhenTrue); return; } } // learn from comparison between non-null and maybe-null, possibly updating maybe-null to non-null BoundExpression? operandComparedToNonNull = null; if (leftType.IsNotNull && rightType.MayBeNull) { operandComparedToNonNull = binary.Right; } else if (rightType.IsNotNull && leftType.MayBeNull) { operandComparedToNonNull = binary.Left; } if (operandComparedToNonNull != null) { switch (op) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.LessThan: case BinaryOperatorKind.GreaterThanOrEqual: case BinaryOperatorKind.LessThanOrEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); SplitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: true); return; case BinaryOperatorKind.NotEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); SplitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: false); return; }; } } private void SplitAndLearnFromNonNullTest(BoundExpression operandComparedToNonNull, bool whenTrue) { var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(operandComparedToNonNull, slotBuilder); if (slotBuilder.Count != 0) { Split(); ref LocalState stateToUpdate = ref whenTrue ? ref this.StateWhenTrue : ref this.StateWhenFalse; MarkSlotsAsNotNull(slotBuilder, ref stateToUpdate); } slotBuilder.Free(); } protected override bool VisitInterpolatedStringHandlerParts(BoundInterpolatedStringBase node, bool usesBoolReturns, bool firstPartIsConditional, ref LocalState shortCircuitState) { var result = base.VisitInterpolatedStringHandlerParts(node, usesBoolReturns, firstPartIsConditional, ref shortCircuitState); SetNotNullResult(node); return result; } protected override void VisitInterpolatedStringBinaryOperatorNode(BoundBinaryOperator node) { SetNotNullResult(node); } /// <summary> /// If we learn that the operand is non-null, we can infer that certain /// sub-expressions were also non-null. /// Get all nested conditional slots for those sub-expressions. For example in a?.b?.c we'll set a, b, and c. /// Only returns slots for tracked expressions. /// </summary> /// <remarks>https://github.com/dotnet/roslyn/issues/53397 This method should potentially be removed.</remarks> private void GetSlotsToMarkAsNotNullable(BoundExpression operand, ArrayBuilder<int> slotBuilder) { Debug.Assert(operand != null); var previousConditionalAccessSlot = _lastConditionalAccessSlot; try { while (true) { // Due to the nature of binding, if there are conditional access they will be at the top of the bound tree, // potentially with a conversion on top of it. We go through any conditional accesses, adding slots for the // conditional receivers if they have them. If we ever get to a receiver that MakeSlot doesn't return a slot // for, nothing underneath is trackable and we bail at that point. Example: // // a?.GetB()?.C // a is a field, GetB is a method, and C is a property // // The top of the tree is the a?.GetB() conditional call. We'll ask for a slot for a, and we'll get one because // fields have slots. The AccessExpression of the BoundConditionalAccess is another BoundConditionalAccess, this time // with a receiver of the GetB() BoundCall. Attempting to get a slot for this receiver will fail, and we'll // return an array with just the slot for a. int slot; switch (operand.Kind) { case BoundKind.Conversion: // https://github.com/dotnet/roslyn/issues/33879 Detect when conversion has a nullable operand operand = ((BoundConversion)operand).Operand; continue; case BoundKind.AsOperator: operand = ((BoundAsOperator)operand).Operand; continue; case BoundKind.ConditionalAccess: var conditional = (BoundConditionalAccess)operand; GetSlotsToMarkAsNotNullable(conditional.Receiver, slotBuilder); slot = MakeSlot(conditional.Receiver); if (slot > 0) { // We need to continue the walk regardless of whether the receiver should be updated. var receiverType = conditional.Receiver.Type!; if (receiverType.IsNullableType()) slot = GetNullableOfTValueSlot(receiverType, slot, out _); } if (slot > 0) { // When MakeSlot is called on the nested AccessExpression, it will recurse through receivers // until it gets to the BoundConditionalReceiver associated with this node. In our override // of MakeSlot, we substitute this slot when we encounter a BoundConditionalReceiver, and reset the // _lastConditionalAccess field. _lastConditionalAccessSlot = slot; operand = conditional.AccessExpression; continue; } // If there's no slot for this receiver, there cannot be another slot for any of the remaining // access expressions. break; default: // Attempt to create a slot for the current thing. If there were any more conditional accesses, // they would have been on top, so this is the last thing we need to specially handle. // https://github.com/dotnet/roslyn/issues/33879 When we handle unconditional access survival (ie after // c.D has been invoked, c must be nonnull or we've thrown a NullRef), revisit whether // we need more special handling here slot = MakeSlot(operand); if (slot > 0 && PossiblyNullableType(operand.Type)) { slotBuilder.Add(slot); } break; } return; } } finally { _lastConditionalAccessSlot = previousConditionalAccessSlot; } } private static bool PossiblyNullableType([NotNullWhen(true)] TypeSymbol? operandType) => operandType?.CanContainNull() == true; private static void MarkSlotsAsNotNull(ArrayBuilder<int> slots, ref LocalState stateToUpdate) { foreach (int slot in slots) { stateToUpdate[slot] = NullableFlowState.NotNull; } } private void LearnFromNonNullTest(BoundExpression expression, ref LocalState state) { if (expression is BoundValuePlaceholderBase placeholder) { if (_resultForPlaceholdersOpt != null && _resultForPlaceholdersOpt.TryGetValue(placeholder, out var value) && value.Replacement != null) { expression = value.Replacement; } else { AssertPlaceholderAllowedWithoutRegistration(placeholder); return; } } var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(expression, slotBuilder); MarkSlotsAsNotNull(slotBuilder, ref state); slotBuilder.Free(); } private void LearnFromNonNullTest(int slot, ref LocalState state) { state[slot] = NullableFlowState.NotNull; } private void LearnFromNullTest(BoundExpression expression, ref LocalState state) { // nothing to learn about a constant if (expression.ConstantValue != null) return; // We should not blindly strip conversions here. Tracked by https://github.com/dotnet/roslyn/issues/36164 var expressionWithoutConversion = RemoveConversion(expression, includeExplicitConversions: true).expression; var slot = MakeSlot(expressionWithoutConversion); // Since we know for sure the slot is null (we just tested it), we know that dependent slots are not // reachable and therefore can be treated as not null. However, we have not computed the proper // (inferred) type for the expression, so we cannot compute the correct symbols for the member slots here // (using the incorrect symbols would result in computing an incorrect default state for them). // Therefore we do not mark dependent slots not null. See https://github.com/dotnet/roslyn/issues/39624 LearnFromNullTest(slot, expressionWithoutConversion.Type, ref state, markDependentSlotsNotNull: false); } private void LearnFromNullTest(int slot, TypeSymbol? expressionType, ref LocalState state, bool markDependentSlotsNotNull) { if (slot > 0 && PossiblyNullableType(expressionType)) { if (state[slot] == NullableFlowState.NotNull) { // Note: We leave a MaybeDefault state as-is state[slot] = NullableFlowState.MaybeNull; } if (markDependentSlotsNotNull) { MarkDependentSlotsNotNull(slot, expressionType, ref state); } } } // If we know for sure that a slot contains a null value, then we know for sure that dependent slots // are "unreachable" so we might as well treat them as not null. That way when this state is merged // with another state, those dependent states won't pollute values from the other state. private void MarkDependentSlotsNotNull(int slot, TypeSymbol expressionType, ref LocalState state, int depth = 2) { if (depth <= 0) return; foreach (var member in getMembers(expressionType)) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var containingType = this._symbol?.ContainingType; if ((member is PropertySymbol { IsIndexedProperty: false } || member.Kind == SymbolKind.Field) && member.RequiresInstanceReceiver() && (containingType is null || AccessCheck.IsSymbolAccessible(member, containingType, ref discardedUseSiteInfo))) { int childSlot = GetOrCreateSlot(member, slot, forceSlotEvenIfEmpty: true, createIfMissing: false); if (childSlot > 0) { state[childSlot] = NullableFlowState.NotNull; MarkDependentSlotsNotNull(childSlot, member.GetTypeOrReturnType().Type, ref state, depth - 1); } } } static IEnumerable<Symbol> getMembers(TypeSymbol type) { // First, return the direct members foreach (var member in type.GetMembers()) yield return member; // All types inherit members from their effective bases for (NamedTypeSymbol baseType = effectiveBase(type); !(baseType is null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) foreach (var member in baseType.GetMembers()) yield return member; // Interfaces and type parameters inherit from their effective interfaces foreach (NamedTypeSymbol interfaceType in inheritedInterfaces(type)) foreach (var member in interfaceType.GetMembers()) yield return member; yield break; static NamedTypeSymbol effectiveBase(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.EffectiveBaseClassNoUseSiteDiagnostics, var t => t.BaseTypeNoUseSiteDiagnostics, }; static ImmutableArray<NamedTypeSymbol> inheritedInterfaces(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.AllEffectiveInterfacesNoUseSiteDiagnostics, { TypeKind: TypeKind.Interface } => type.AllInterfacesNoUseSiteDiagnostics, _ => ImmutableArray<NamedTypeSymbol>.Empty, }; } } private static BoundExpression SkipReferenceConversions(BoundExpression possiblyConversion) { while (possiblyConversion.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)possiblyConversion; switch (conversion.ConversionKind) { case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: possiblyConversion = conversion.Operand; break; default: return possiblyConversion; } } return possiblyConversion; } public override BoundNode? VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; int leftSlot = MakeSlot(leftOperand); TypeWithAnnotations targetType = VisitLvalueWithAnnotations(leftOperand); var leftState = this.State.Clone(); LearnFromNonNullTest(leftOperand, ref leftState); LearnFromNullTest(leftOperand, ref this.State); if (node.IsNullableValueTypeAssignment) { targetType = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); } TypeWithState rightResult = VisitOptionalImplicitConversion(rightOperand, targetType, useLegacyWarnings: UseLegacyWarnings(leftOperand, targetType), trackMembers: false, AssignmentKind.Assignment); TrackNullableStateForAssignment(rightOperand, targetType, leftSlot, rightResult, MakeSlot(rightOperand)); Join(ref this.State, ref leftState); TypeWithState resultType = TypeWithState.Create(targetType.Type, rightResult.State); SetResultType(node, resultType); return null; } public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { Debug.Assert(!IsConditionalState); BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; if (IsConstantNull(leftOperand)) { VisitRvalue(leftOperand); Visit(rightOperand); var rightUnconditionalResult = ResultType; // Should be able to use rightResult for the result of the operator but // binding may have generated a different result type in the case of errors. SetResultType(node, TypeWithState.Create(node.Type, rightUnconditionalResult.State)); return null; } VisitPossibleConditionalAccess(leftOperand, out var whenNotNull); TypeWithState leftResult = ResultType; Unsplit(); LearnFromNullTest(leftOperand, ref this.State); bool leftIsConstant = leftOperand.ConstantValue != null; if (leftIsConstant) { SetUnreachable(); } Visit(rightOperand); TypeWithState rightResult = ResultType; Join(ref whenNotNull); var leftResultType = leftResult.Type; var rightResultType = rightResult.Type; var (resultType, leftState) = node.OperatorResultKind switch { BoundNullCoalescingOperatorResultKind.NoCommonType => (node.Type, NullableFlowState.NotNull), BoundNullCoalescingOperatorResultKind.LeftType => getLeftResultType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedType => getLeftResultType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightType => getResultStateWithRightType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedRightType => getResultStateWithRightType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightDynamicType => (rightResultType!, NullableFlowState.NotNull), _ => throw ExceptionUtilities.UnexpectedValue(node.OperatorResultKind), }; SetResultType(node, TypeWithState.Create(resultType, rightResult.State.Join(leftState))); return null; (TypeSymbol ResultType, NullableFlowState LeftState) getLeftResultType(TypeSymbol leftType, TypeSymbol rightType) { Debug.Assert(rightType is object); // If there was an identity conversion between the two operands (in short, if there // is no implicit conversion on the right operand), then check nullable conversions // in both directions since it's possible the right operand is the better result type. if ((node.RightOperand as BoundConversion)?.ExplicitCastInCode != false && GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: false, isChecked: node.Checked) is { Exists: true } conversion) { Debug.Assert(!conversion.IsUserDefined); return (rightType, NullableFlowState.NotNull); } conversion = GenerateConversionForConditionalOperator(node.RightOperand, rightType, leftType, reportMismatch: true, isChecked: node.Checked); Debug.Assert(!conversion.IsUserDefined); return (leftType, NullableFlowState.NotNull); } (TypeSymbol ResultType, NullableFlowState LeftState) getResultStateWithRightType(TypeSymbol leftType, TypeSymbol rightType) { var conversion = GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: true, isChecked: node.Checked); if (conversion.IsUserDefined) { var conversionResult = VisitConversion( conversionOpt: null, node.LeftOperand, conversion, TypeWithAnnotations.Create(rightType), // When considering the conversion on the left node, it can only occur in the case where the underlying // execution returned non-null TypeWithState.Create(leftType, NullableFlowState.NotNull), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: false); Debug.Assert(conversionResult.Type is not null); return (conversionResult.Type!, conversionResult.State); } return (rightType, NullableFlowState.NotNull); } } /// <summary> /// Visits a node only if it is a conditional access. /// Returns 'true' if and only if the node was visited. /// </summary> private bool TryVisitConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { var (operand, conversion) = RemoveConversion(node, includeExplicitConversions: true); if (operand is not BoundConditionalAccess access || !CanPropagateStateWhenNotNull(conversion)) { stateWhenNotNull = default; return false; } Unsplit(); VisitConditionalAccess(access, out stateWhenNotNull); if (node is BoundConversion boundConversion) { var operandType = ResultType; TypeWithAnnotations explicitType = boundConversion.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(boundConversion.Type); Debug.Assert(targetType.HasType); var result = VisitConversion(boundConversion, access, conversion, targetType, operandType, checkConversion: true, fromExplicitCast, useLegacyWarnings: true, assignmentKind: AssignmentKind.Assignment); SetResultType(boundConversion, result); } Debug.Assert(!IsConditionalState); return true; } /// <summary> /// Unconditionally visits an expression and returns the "state when not null" for the expression. /// </summary> private bool VisitPossibleConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { if (TryVisitConditionalAccess(node, out stateWhenNotNull)) { return true; } // in case we *didn't* have a conditional access, the only thing we learn in the "state when not null" // is that the top-level expression was non-null. Visit(node); stateWhenNotNull = PossiblyConditionalState.Create(this); (node, _) = RemoveConversion(node, includeExplicitConversions: true); var slot = MakeSlot(node); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenTrue); LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenFalse); } else { LearnFromNonNullTest(slot, ref stateWhenNotNull.State); } } return false; } private void VisitConditionalAccess(BoundConditionalAccess node, out PossiblyConditionalState stateWhenNotNull) { Debug.Assert(!IsConditionalState); var receiver = node.Receiver; // handle scenarios like `(a?.b)?.c()` VisitPossibleConditionalAccess(receiver, out stateWhenNotNull); Unsplit(); _currentConditionalReceiverVisitResult = _visitResult; var previousConditionalAccessSlot = _lastConditionalAccessSlot; if (receiver.ConstantValue is { IsNull: false }) { // Consider a scenario like `"a"?.M0(x = 1)?.M0(y = 1)`. // We can "know" that `.M0(x = 1)` was evaluated unconditionally but not `M0(y = 1)`. // Therefore we do a VisitPossibleConditionalAccess here which unconditionally includes the "after receiver" state in State // and includes the "after subsequent conditional accesses" in stateWhenNotNull VisitPossibleConditionalAccess(node.AccessExpression, out stateWhenNotNull); } else { var savedState = this.State.Clone(); if (IsConstantNull(receiver)) { SetUnreachable(); _lastConditionalAccessSlot = -1; } else { // In the when-null branch, the receiver is known to be maybe-null. // In the other branch, the receiver is known to be non-null. LearnFromNullTest(receiver, ref savedState); makeAndAdjustReceiverSlot(receiver); SetPossiblyConditionalState(stateWhenNotNull); } // We want to preserve stateWhenNotNull from accesses in the same "chain": // a?.b(out x)?.c(out y); // expected to preserve stateWhenNotNull from both ?.b(out x) and ?.c(out y) // but not accesses in nested expressions: // a?.b(out x, c?.d(out y)); // expected to preserve stateWhenNotNull from a?.b(out x, ...) but not from c?.d(out y) BoundExpression expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // we assume that non-conditional accesses can never contain conditional accesses from the same "chain". // that is, we never have to dig through non-conditional accesses to find and handle conditional accesses. Debug.Assert(innerCondAccess.Receiver is not (BoundConditionalAccess or BoundConversion)); VisitRvalue(innerCondAccess.Receiver); _currentConditionalReceiverVisitResult = _visitResult; makeAndAdjustReceiverSlot(innerCondAccess.Receiver); // The savedState here represents the scenario where 0 or more of the access expressions could have been evaluated. // e.g. after visiting `a?.b(x = null)?.c(x = new object())`, the "state when not null" of `x` is NotNull, but the "state when maybe null" of `x` is MaybeNull. Join(ref savedState, ref State); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); Visit(expr); expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // The resulting nullability of each nested conditional access is the same as the resulting nullability of the rightmost access. SetAnalyzedNullability(innerCondAccess, _visitResult); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); var slot = MakeSlot(expr); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref StateWhenTrue); LearnFromNonNullTest(slot, ref StateWhenFalse); } else { LearnFromNonNullTest(slot, ref State); } } stateWhenNotNull = PossiblyConditionalState.Create(this); Unsplit(); Join(ref this.State, ref savedState); } var accessTypeWithAnnotations = LvalueResultType; TypeSymbol accessType = accessTypeWithAnnotations.Type; var oldType = node.Type; var resultType = oldType.IsVoidType() || oldType.IsErrorType() ? oldType : oldType.IsNullableType() && !accessType.IsNullableType() ? MakeNullableOf(accessTypeWithAnnotations) : accessType; // Per LDM 2019-02-13 decision, the result of a conditional access "may be null" even if // both the receiver and right-hand-side are believed not to be null. SetResultType(node, TypeWithState.Create(resultType, NullableFlowState.MaybeDefault)); _currentConditionalReceiverVisitResult = default; _lastConditionalAccessSlot = previousConditionalAccessSlot; void makeAndAdjustReceiverSlot(BoundExpression receiver) { var slot = MakeSlot(receiver); if (slot > -1) LearnFromNonNullTest(slot, ref State); // given `a?.b()`, when `a` is a nullable value type, // the conditional receiver for `?.b()` must be linked to `a.Value`, not to `a`. if (slot > 0 && receiver.Type?.IsNullableType() == true) slot = GetNullableOfTValueSlot(receiver.Type, slot, out _); _lastConditionalAccessSlot = slot; } } public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) { VisitConditionalAccess(node, out _); return null; } protected override BoundNode? VisitConditionalOperatorCore( BoundExpression node, bool isRef, BoundExpression condition, BoundExpression originalConsequence, BoundExpression originalAlternative) { VisitCondition(condition); var consequenceState = this.StateWhenTrue; var alternativeState = this.StateWhenFalse; TypeWithState consequenceRValue; TypeWithState alternativeRValue; if (isRef) { TypeWithAnnotations consequenceLValue; TypeWithAnnotations alternativeLValue; (consequenceLValue, consequenceRValue) = visitConditionalRefOperand(consequenceState, originalConsequence); consequenceState = this.State; (alternativeLValue, alternativeRValue) = visitConditionalRefOperand(alternativeState, originalAlternative); Join(ref this.State, ref consequenceState); TypeSymbol? refResultType = node.Type?.SetUnknownNullabilityForReferenceTypes(); if (IsNullabilityMismatch(consequenceLValue, alternativeLValue)) { // l-value types must match ReportNullabilityMismatchInAssignment(node.Syntax, consequenceLValue, alternativeLValue); } else if (!node.HasErrors) { refResultType = consequenceRValue.Type!.MergeEquivalentTypes(alternativeRValue.Type, VarianceKind.None); } var lValueAnnotation = consequenceLValue.NullableAnnotation.EnsureCompatible(alternativeLValue.NullableAnnotation); var rValueState = consequenceRValue.State.Join(alternativeRValue.State); SetResult(node, TypeWithState.Create(refResultType, rValueState), TypeWithAnnotations.Create(refResultType, lValueAnnotation)); return null; } (var consequence, var consequenceConversion, consequenceRValue) = visitConditionalOperand(consequenceState, originalConsequence); var consequenceConditionalState = PossiblyConditionalState.Create(this); consequenceState = CloneAndUnsplit(ref consequenceConditionalState); var consequenceEndReachable = consequenceState.Reachable; (var alternative, var alternativeConversion, alternativeRValue) = visitConditionalOperand(alternativeState, originalAlternative); var alternativeConditionalState = PossiblyConditionalState.Create(this); alternativeState = CloneAndUnsplit(ref alternativeConditionalState); var alternativeEndReachable = alternativeState.Reachable; SetPossiblyConditionalState(in consequenceConditionalState); Join(ref alternativeConditionalState); TypeSymbol? resultType; bool wasTargetTyped = node is BoundConditionalOperator { WasTargetTyped: true }; if (node.HasErrors || wasTargetTyped) { resultType = null; } else { // Determine nested nullability using BestTypeInferrer. // If a branch is unreachable, we could use the nested nullability of the other // branch, but that requires using the nullability of the branch as it applies to the // target type. For instance, the result of the conditional in the following should // be `IEnumerable<object>` not `object[]`: // object[] a = ...; // IEnumerable<object?> b = ...; // var c = true ? a : b; BoundExpression consequencePlaceholder = CreatePlaceholderIfNecessary(consequence, consequenceRValue.ToTypeWithAnnotations(compilation)); BoundExpression alternativePlaceholder = CreatePlaceholderIfNecessary(alternative, alternativeRValue.ToTypeWithAnnotations(compilation)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; resultType = BestTypeInferrer.InferBestTypeForConditionalOperator(consequencePlaceholder, alternativePlaceholder, _conversions, out _, ref discardedUseSiteInfo); } resultType ??= node.Type?.SetUnknownNullabilityForReferenceTypes(); TypeWithAnnotations resultTypeWithAnnotations; if (resultType is null) { if (!wasTargetTyped) { // This can happen when we're inferring the return type of a lambda. For this case, we don't need to do any work, // the unconverted conditional operator can't contribute info. The conversion that should be on top of this // can add or remove nullability, and nested nodes aren't being publicly exposed by the semantic model. Debug.Assert(node is BoundUnconvertedConditionalOperator); Debug.Assert(_returnTypesOpt is not null); SetResultType(node, TypeWithState.Create(resultType, default)); return null; } resultTypeWithAnnotations = default; } else { resultTypeWithAnnotations = TypeWithAnnotations.Create(resultType); } TypeWithState typeWithState = convertArms( node, originalConsequence, originalAlternative, consequenceState, alternativeState, consequenceRValue, alternativeRValue, consequence, consequenceConversion, consequenceEndReachable, alternative, alternativeConversion, alternativeEndReachable, resultTypeWithAnnotations, wasTargetTyped); SetResultType(node, typeWithState, updateAnalyzedNullability: false); return null; TypeWithState convertArms( BoundExpression node, BoundExpression originalConsequence, BoundExpression originalAlternative, LocalState consequenceState, LocalState alternativeState, TypeWithState consequenceRValue, TypeWithState alternativeRValue, BoundExpression consequence, Conversion consequenceConversion, bool consequenceEndReachable, BoundExpression alternative, Conversion alternativeConversion, bool alternativeEndReachable, TypeWithAnnotations resultTypeWithAnnotations, bool wasTargetTyped) { NullableFlowState resultState; if (!wasTargetTyped) { TypeWithState convertedConsequenceResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalConsequence, consequence, consequenceConversion, resultTypeWithAnnotations, consequenceRValue, consequenceState, consequenceEndReachable); TypeWithState convertedAlternativeResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalAlternative, alternative, alternativeConversion, resultTypeWithAnnotations, alternativeRValue, alternativeState, alternativeEndReachable); resultState = convertedConsequenceResult.State.Join(convertedAlternativeResult.State); var typeWithState = TypeWithState.Create(resultTypeWithAnnotations.Type, resultState); SetAnalyzedNullability(node, typeWithState); return typeWithState; } else { addConvertArmsAsCompletion( node, originalConsequence, originalAlternative, consequenceState, alternativeState, consequenceRValue, alternativeRValue, consequence, consequenceConversion, consequenceEndReachable, alternative, alternativeConversion, alternativeEndReachable); resultState = consequenceRValue.State.Join(alternativeRValue.State); return TypeWithState.Create(resultTypeWithAnnotations.Type, resultState); } } void addConvertArmsAsCompletion( BoundExpression node, BoundExpression originalConsequence, BoundExpression originalAlternative, LocalState consequenceState, LocalState alternativeState, TypeWithState consequenceRValue, TypeWithState alternativeRValue, BoundExpression consequence, Conversion consequenceConversion, bool consequenceEndReachable, BoundExpression alternative, Conversion alternativeConversion, bool alternativeEndReachable) { TargetTypedAnalysisCompletion[node] = (TypeWithAnnotations resultTypeWithAnnotations) => { return convertArms( node, originalConsequence, originalAlternative, consequenceState, alternativeState, consequenceRValue, alternativeRValue, consequence, consequenceConversion, consequenceEndReachable, alternative, alternativeConversion, alternativeEndReachable, resultTypeWithAnnotations, wasTargetTyped: false); }; } (BoundExpression, Conversion, TypeWithState) visitConditionalOperand(LocalState state, BoundExpression operand) { Conversion conversion; SetState(state); Debug.Assert(!isRef); BoundExpression operandNoConversion; (operandNoConversion, conversion) = RemoveConversion(operand, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(operand, operandNoConversion); Visit(operandNoConversion); return (operandNoConversion, conversion, ResultType); } (TypeWithAnnotations LValueType, TypeWithState RValueType) visitConditionalRefOperand(LocalState state, BoundExpression operand) { SetState(state); Debug.Assert(isRef); TypeWithAnnotations lValueType = VisitLvalueWithAnnotations(operand); return (lValueType, ResultType); } } private TypeWithState ConvertConditionalOperandOrSwitchExpressionArmResult( BoundExpression node, BoundExpression operand, Conversion conversion, TypeWithAnnotations targetType, TypeWithState operandType, LocalState state, bool isReachable) { var savedState = this.State; this.State = state; bool previousDisabledDiagnostics = _disableDiagnostics; // If the node is not reachable, then we're only visiting to get // nullability information for the public API, and not to produce diagnostics. // Disable diagnostics, and return default for the resulting state // to indicate that warnings were suppressed. if (!isReachable) { _disableDiagnostics = true; } var resultType = VisitConversion( GetConversionIfApplicable(node, operand), operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false); if (!isReachable) { resultType = default; _disableDiagnostics = previousDisabledDiagnostics; } this.State = savedState; return resultType; } private bool IsReachable() => this.IsConditionalState ? (this.StateWhenTrue.Reachable || this.StateWhenFalse.Reachable) : this.State.Reachable; /// <summary> /// Placeholders are bound expressions with type and state. /// But for typeless expressions (such as `null` or `(null, null)` we hold onto the original bound expression, /// as it will be useful for conversions from expression. /// </summary> private static BoundExpression CreatePlaceholderIfNecessary(BoundExpression expr, TypeWithAnnotations type) { return !type.HasType ? expr : new BoundExpressionWithNullability(expr.Syntax, expr, type.NullableAnnotation, type.Type); } public override BoundNode? VisitConditionalReceiver(BoundConditionalReceiver node) { var rvalueType = _currentConditionalReceiverVisitResult.RValueType.Type; if (rvalueType?.IsNullableType() == true) { rvalueType = rvalueType.GetNullableUnderlyingType(); } SetResultType(node, TypeWithState.Create(rvalueType, NullableFlowState.NotNull)); return null; } public override BoundNode? VisitCall(BoundCall node) { // Note: we analyze even omitted calls TypeWithState receiverType = VisitCallReceiver(node); ReinferMethodAndVisitArguments(node, receiverType); return null; } private void ReinferMethodAndVisitArguments(BoundCall node, TypeWithState receiverType) { var method = node.Method; ImmutableArray<RefKind> refKindsOpt = node.ArgumentRefKindsOpt; if (!receiverType.HasNullType) { // Update method based on inferred receiver type. method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } ImmutableArray<VisitArgumentResult> results; bool returnNotNull; (method, results, returnNotNull) = VisitArguments(node, node.Arguments, refKindsOpt, method!.Parameters, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod, method); ApplyMemberPostConditions(node.ReceiverOpt, method); LearnFromEqualsMethod(method, node, receiverType, results); var returnState = GetReturnTypeWithState(method); if (returnNotNull) { returnState = returnState.WithNotNullState(); } SetResult(node, returnState, method.ReturnTypeWithAnnotations); SetUpdatedSymbol(node, node.Method, method); } private void LearnFromEqualsMethod(MethodSymbol method, BoundCall node, TypeWithState receiverType, ImmutableArray<VisitArgumentResult> results) { // easy out var parameterCount = method.ParameterCount; var arguments = node.Arguments; if (node.HasErrors || (parameterCount != 1 && parameterCount != 2) || parameterCount != arguments.Length || method.MethodKind != MethodKind.Ordinary || method.ReturnType.SpecialType != SpecialType.System_Boolean || (method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__Equals).Name && method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__ReferenceEquals).Name && !anyOverriddenMethodHasExplicitImplementation(method))) { return; } var isStaticEqualsMethod = method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__EqualsObjectObject)) || method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__ReferenceEquals)); if (isStaticEqualsMethod || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_Collections_Generic_IEqualityComparer_T__Equals)) { Debug.Assert(arguments.Length == 2); learnFromEqualsMethodArguments(arguments[0], results[0].RValueType, arguments[1], results[1].RValueType); return; } var isObjectEqualsMethodOrOverride = method.GetLeastOverriddenMethod(accessingTypeOpt: null) .Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__Equals)); if (node.ReceiverOpt is BoundExpression receiver && (isObjectEqualsMethodOrOverride || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_IEquatable_T__Equals))) { Debug.Assert(arguments.Length == 1); learnFromEqualsMethodArguments(receiver, receiverType, arguments[0], results[0].RValueType); return; } static bool anyOverriddenMethodHasExplicitImplementation(MethodSymbol method) { for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.IsExplicitInterfaceImplementation) { return true; } } return false; } static bool isWellKnownEqualityMethodOrImplementation(CSharpCompilation compilation, MethodSymbol method, TypeSymbol? receiverType, WellKnownMember wellKnownMember) { var wellKnownMethod = (MethodSymbol?)compilation.GetWellKnownTypeMember(wellKnownMember); if (wellKnownMethod is null || receiverType is null) { return false; } var wellKnownType = wellKnownMethod.ContainingType; var parameterType = method.Parameters[0].TypeWithAnnotations; var constructedType = wellKnownType.Construct(ImmutableArray.Create(parameterType)); var constructedMethod = wellKnownMethod.AsMember(constructedType); // FindImplementationForInterfaceMember doesn't check if this method is itself the interface method we're looking for if (constructedMethod.Equals(method)) { return true; } // check whether 'method', when called on this receiver, is an implementation of 'constructedMethod'. for (var baseType = receiverType; baseType is object && method is object; baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var implementationMethod = baseType.FindImplementationForInterfaceMember(constructedMethod); if (implementationMethod is null) { // we know no base type will implement this interface member either return false; } if (implementationMethod.ContainingType.IsInterface) { // this method cannot be called directly from source because an interface can only explicitly implement a method from its base interface. return false; } // could be calling an override of a method that implements the interface method for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.Equals(implementationMethod)) { return true; } } // the Equals method being called isn't the method that implements the interface method in this type. // it could be a method that implements the interface on a base type, so check again with the base type of 'implementationMethod.ContainingType' // e.g. in this hierarchy: // class A -> B -> C -> D // method virtual B.Equals -> override D.Equals // // we would potentially check: // 1. D.Equals when called on D, then B.Equals when called on D // 2. B.Equals when called on C // 3. B.Equals when called on B // 4. give up when checking A, since B.Equals is not overriding anything in A // we know that implementationMethod.ContainingType is the same type or a base type of 'baseType', // and that the implementation method will be the same between 'baseType' and 'implementationMethod.ContainingType'. // we step through the intermediate bases in order to skip unnecessary override methods. while (!baseType.Equals(implementationMethod.ContainingType) && method is object) { if (baseType.Equals(method.ContainingType)) { // since we're about to move on to the base of 'method.ContainingType', // we know the implementation could only be an overridden method of 'method'. method = method.OverriddenMethod; } baseType = baseType.BaseTypeNoUseSiteDiagnostics; // the implementation method must be contained in this 'baseType' or one of its bases. Debug.Assert(baseType is object); } // now 'baseType == implementationMethod.ContainingType', so if 'method' is // contained in that same type we should advance 'method' one more time. if (method is object && baseType.Equals(method.ContainingType)) { method = method.OverriddenMethod; } } return false; } void learnFromEqualsMethodArguments(BoundExpression left, TypeWithState leftType, BoundExpression right, TypeWithState rightType) { // comparing anything to a null literal gives maybe-null when true and not-null when false // comparing a maybe-null to a not-null gives us not-null when true, nothing learned when false if (left.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(right, ref StateWhenTrue); LearnFromNonNullTest(right, ref StateWhenFalse); } else if (right.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(left, ref StateWhenTrue); LearnFromNonNullTest(left, ref StateWhenFalse); } else if (leftType.MayBeNull && rightType.IsNotNull) { Split(); LearnFromNonNullTest(left, ref StateWhenTrue); } else if (rightType.MayBeNull && leftType.IsNotNull) { Split(); LearnFromNonNullTest(right, ref StateWhenTrue); } } } private bool IsCompareExchangeMethod(MethodSymbol? method) { if (method is null) { return false; } return method.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange), SymbolEqualityComparer.ConsiderEverything.CompareKind) || method.OriginalDefinition.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T), SymbolEqualityComparer.ConsiderEverything.CompareKind); } private readonly struct CompareExchangeInfo { public readonly ImmutableArray<BoundExpression> Arguments; public readonly ImmutableArray<VisitArgumentResult> Results; public readonly ImmutableArray<int> ArgsToParamsOpt; public CompareExchangeInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> results, ImmutableArray<int> argsToParamsOpt) { Arguments = arguments; Results = results; ArgsToParamsOpt = argsToParamsOpt; } public bool IsDefault => Arguments.IsDefault || Results.IsDefault; } private NullableFlowState LearnFromCompareExchangeMethod(in CompareExchangeInfo compareExchangeInfo) { Debug.Assert(!compareExchangeInfo.IsDefault); // In general a call to CompareExchange of the form: // // Interlocked.CompareExchange(ref location, value, comparand); // // will be analyzed similarly to the following: // // if (location == comparand) // { // location = value; // } if (compareExchangeInfo.Arguments.Length != 3) { // This can occur if CompareExchange has optional arguments. // Since none of the main runtimes have optional arguments, // we bail to avoid an exception but don't bother actually calculating the FlowState. return NullableFlowState.NotNull; } var argsToParamsOpt = compareExchangeInfo.ArgsToParamsOpt; Debug.Assert(argsToParamsOpt is { IsDefault: true } or { Length: 3 }); var (comparandIndex, valueIndex, locationIndex) = argsToParamsOpt.IsDefault ? (2, 1, 0) : (argsToParamsOpt.IndexOf(2), argsToParamsOpt.IndexOf(1), argsToParamsOpt.IndexOf(0)); var comparand = compareExchangeInfo.Arguments[comparandIndex]; var valueFlowState = compareExchangeInfo.Results[valueIndex].RValueType.State; if (comparand.ConstantValue?.IsNull == true) { // If location contained a null, then the write `location = value` definitely occurred } else { var locationFlowState = compareExchangeInfo.Results[locationIndex].RValueType.State; // A write may have occurred valueFlowState = valueFlowState.Join(locationFlowState); } return valueFlowState; } private TypeWithState VisitCallReceiver(BoundCall node) { var receiverOpt = node.ReceiverOpt; TypeWithState receiverType = default; if (receiverOpt != null) { receiverType = VisitRvalueWithState(receiverOpt); // methods which are members of Nullable<T> (ex: ToString, GetHashCode) can be invoked on null receiver. // However, inherited methods (ex: GetType) are invoked on a boxed value (since base types are reference types) // and therefore in those cases nullable receivers should be checked for nullness. bool checkNullableValueType = false; var type = receiverType.Type; var method = node.Method; if (method.RequiresInstanceReceiver && type?.IsNullableType() == true && method.ContainingType.IsReferenceType) { checkNullableValueType = true; } else if (method.OriginalDefinition == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { // call to get_Value may not occur directly in source, but may be inserted as a result of premature lowering. // One example where we do it is foreach with nullables. // The reason is Dev10 compatibility (see: UnwrapCollectionExpressionIfNullable in ForEachLoopBinder.cs) // Regardless of the reasons, we know that the method does not tolerate nulls. checkNullableValueType = true; } // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType); } return receiverType; } private TypeWithState GetReturnTypeWithState(MethodSymbol method) { return TypeWithState.Create(method.ReturnTypeWithAnnotations, GetRValueAnnotations(method)); } private FlowAnalysisAnnotations GetRValueAnnotations(Symbol? symbol) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = symbol.GetFlowAnalysisAnnotations(); return annotations & (FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull); } private FlowAnalysisAnnotations GetParameterAnnotations(ParameterSymbol parameter) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) return IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : parameter.FlowAnalysisAnnotations; } /// <summary> /// Fix a TypeWithAnnotations based on Allow/DisallowNull annotations prior to a conversion or assignment. /// Note this does not work for nullable value types, so an additional check with <see cref="CheckDisallowedNullAssignment"/> may be required. /// </summary> private static TypeWithAnnotations ApplyLValueAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations flowAnalysisAnnotations) { if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.DisallowNull) == FlowAnalysisAnnotations.DisallowNull) { return declaredType.AsNotAnnotated(); } else if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.AllowNull) == FlowAnalysisAnnotations.AllowNull) { return declaredType.AsAnnotated(); } return declaredType; } /// <summary> /// Update the null-state based on MaybeNull/NotNull /// </summary> private static TypeWithState ApplyUnconditionalAnnotations(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } return typeWithState; } private static TypeWithAnnotations ApplyUnconditionalAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return declaredType.AsAnnotated(); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return declaredType.AsNotAnnotated(); } return declaredType; } // https://github.com/dotnet/roslyn/issues/29863 Record in the node whether type // arguments were implicit, to allow for cases where the syntax is not an // invocation (such as a synthesized call from a query interpretation). private static bool HasImplicitTypeArguments(BoundNode node) { if (node is BoundCollectionElementInitializer { AddMethod: { TypeArgumentsWithAnnotations: { IsEmpty: false } } }) { return true; } if (node is BoundForEachStatement { EnumeratorInfoOpt: { GetEnumeratorInfo: { Method: { TypeArgumentsWithAnnotations: { IsEmpty: false } } } } }) { return true; } var syntax = node.Syntax; if (syntax.Kind() != SyntaxKind.InvocationExpression) { // Unexpected syntax kind. return false; } return HasImplicitTypeArguments(((InvocationExpressionSyntax)syntax).Expression); } private static bool HasImplicitTypeArguments(SyntaxNode syntax) { var nameSyntax = Binder.GetNameSyntax(syntax, out _); if (nameSyntax == null) { // Unexpected syntax kind. return false; } nameSyntax = nameSyntax.GetUnqualifiedName(); return nameSyntax.Kind() != SyntaxKind.GenericName; } protected override void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { // Callers should be using VisitArguments overload below. throw ExceptionUtilities.Unreachable; } private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol? method, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod) { return VisitArguments(node, arguments, refKindsOpt, method is null ? default : method.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method); } private ImmutableArray<VisitArgumentResult> VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, PropertySymbol? property, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { return VisitArguments(node, arguments, refKindsOpt, property is null ? default : property.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod: false).results; } /// <summary> /// If you pass in a method symbol, its type arguments will be re-inferred and the re-inferred method will be returned. /// </summary> private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method = null) { var result = VisitArguments(node, arguments, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method, delayCompletionForTargetMember: false); Debug.Assert(result.completion is null); return (result.method, result.results, result.returnNotNull); } private delegate (MethodSymbol? method, bool returnNotNull) ArgumentsCompletionDelegate(ImmutableArray<VisitArgumentResult> argumentResults, ImmutableArray<ParameterSymbol> parametersOpt, MethodSymbol? method); private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull, ArgumentsCompletionDelegate? completion) VisitArguments( BoundNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method, bool delayCompletionForTargetMember) { Debug.Assert(!arguments.IsDefault); (ImmutableArray<BoundExpression> argumentsNoConversions, ImmutableArray<Conversion> conversions) = RemoveArgumentConversions(arguments, refKindsOpt); // Visit the arguments and collect results ImmutableArray<VisitArgumentResult> results = VisitArgumentsEvaluate(argumentsNoConversions, refKindsOpt, GetParametersAnnotations(arguments, parametersOpt, argsToParamsOpt, expanded), defaultArguments); return visitArguments( node, arguments, argumentsNoConversions, conversions, results, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method, delayCompletionForTargetMember); (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull, ArgumentsCompletionDelegate? completion) visitArguments( BoundNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<BoundExpression> argumentsNoConversions, ImmutableArray<Conversion> conversions, ImmutableArray<VisitArgumentResult> results, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method, bool delayCompletionForTargetMember) { bool shouldReturnNotNull = false; if (delayCompletionForTargetMember) { return (method, results, shouldReturnNotNull, visitArgumentsAsContinuation( node, arguments, argumentsNoConversions, conversions, refKindsOpt, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod)); } // Re-infer method type parameters if (method?.IsGenericMethod == true) { if (HasImplicitTypeArguments(node)) { method = InferMethodTypeArguments(method, GetArgumentsForMethodTypeInference(results, argumentsNoConversions), refKindsOpt, argsToParamsOpt, expanded); parametersOpt = method.Parameters; } if (ConstraintsHelper.RequiresChecking(method)) { var syntax = node.Syntax; CheckMethodConstraints( syntax switch { InvocationExpressionSyntax { Expression: var expression } => expression, ForEachStatementSyntax { Expression: var expression } => expression, _ => syntax }, method); } } bool parameterHasNotNullIfNotNull = !IsAnalyzingAttribute && !parametersOpt.IsDefault && parametersOpt.Any(static p => !p.NotNullIfParameterNotNull.IsEmpty); var notNullParametersBuilder = parameterHasNotNullIfNotNull ? ArrayBuilder<ParameterSymbol>.GetInstance() : null; var conversionResultsBuilder = ArrayBuilder<VisitResult>.GetInstance(results.Length); if (!parametersOpt.IsDefault) { // Visit conversions, inbound assignments including pre-conditions ImmutableHashSet<string>? returnNotNullIfParameterNotNull = IsAnalyzingAttribute ? null : method?.ReturnNotNullIfParameterNotNull; for (int i = 0; i < results.Length; i++) { var argumentNoConversion = argumentsNoConversions[i]; var argument = i < arguments.Length ? arguments[i] : argumentNoConversion; if (argument is not BoundConversion && argumentNoConversion is BoundLambda lambda) { Debug.Assert(node.HasErrors); Debug.Assert((object)argument == argumentNoConversion); // 'VisitConversion' only visits a lambda when the lambda has an AnonymousFunction conversion. // This lambda doesn't have a conversion, so we need to visit it here. VisitLambda(lambda, delegateTypeOpt: null, results[i].StateForLambda); continue; } (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, bool isExpandedParamsArgument) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { // If this assert fails, we are missing necessary info to visit the // conversion of a target typed construct. Debug.Assert(!IsTargetTypedExpression(argumentNoConversion) || _targetTypedAnalysisCompletionOpt?.ContainsKey(argumentNoConversion) is true); // If this assert fails, it means we failed to visit a lambda for error recovery above. Debug.Assert(argumentNoConversion is not BoundLambda); continue; } // We disable diagnostics when: // 1. the containing call has errors (to reduce cascading diagnostics) // 2. on implicit default arguments (since that's really only an issue with the declaration) var previousDisableDiagnostics = _disableDiagnostics; _disableDiagnostics |= node.HasErrors || defaultArguments[i]; VisitArgumentConversionAndInboundAssignmentsAndPreConditions( GetConversionIfApplicable(argument, argumentNoConversion), argumentNoConversion, conversions.IsDefault || i >= conversions.Length ? Conversion.Identity : conversions[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], conversionResultsBuilder, invokedAsExtensionMethod && i == 0); _disableDiagnostics = previousDisableDiagnostics; if (results[i].RValueType.IsNotNull || isExpandedParamsArgument) { notNullParametersBuilder?.Add(parameter); if (returnNotNullIfParameterNotNull?.Contains(parameter.Name) == true) { shouldReturnNotNull = true; } } } } conversionResultsBuilder.Free(); if (node is BoundCall { Method: { OriginalDefinition: LocalFunctionSymbol localFunction } }) { VisitLocalFunctionUse(localFunction); } if (!node.HasErrors && !parametersOpt.IsDefault) { // For CompareExchange method we need more context to determine the state of outbound assignment CompareExchangeInfo compareExchangeInfo = IsCompareExchangeMethod(method) ? new CompareExchangeInfo(arguments, results, argsToParamsOpt) : default; // Visit outbound assignments and post-conditions // Note: the state may get split in this step for (int i = 0; i < arguments.Length; i++) { (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { continue; } VisitArgumentOutboundAssignmentsAndPostConditions( arguments[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], notNullParametersBuilder, (!compareExchangeInfo.IsDefault && parameter.Ordinal == 0) ? compareExchangeInfo : default); } } else { for (int i = 0; i < arguments.Length; i++) { // We can hit this case when dynamic methods are involved, or when there are errors. In either case we have no information, // so just assume that the conversions have the same nullability as the underlying result var argument = arguments[i]; var result = results[i]; var argumentNoConversion = argumentsNoConversions[i]; TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState.Create(argument.Type, result.RValueType.State), argument as BoundConversion, argumentNoConversion); } } if (!IsAnalyzingAttribute && method is object && (method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) { SetUnreachable(); } notNullParametersBuilder?.Free(); return (method, results, shouldReturnNotNull, null); } ArgumentsCompletionDelegate visitArgumentsAsContinuation( BoundNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<BoundExpression> argumentsNoConversions, ImmutableArray<Conversion> conversions, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod) { return (ImmutableArray<VisitArgumentResult> results, ImmutableArray<ParameterSymbol> parametersOpt, MethodSymbol? method) => { var result = visitArguments( node, arguments, argumentsNoConversions, conversions, results, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method, delayCompletionForTargetMember: false); Debug.Assert(result.completion is null); return (result.method, result.returnNotNull); }; } } private void ApplyMemberPostConditions(BoundExpression? receiverOpt, MethodSymbol? method) { if (method is null) { return; } int receiverSlot = method.IsStatic ? 0 : receiverOpt is null ? -1 : MakeSlot(receiverOpt); if (receiverSlot < 0) { return; } ApplyMemberPostConditions(receiverSlot, method); } private void ApplyMemberPostConditions(int receiverSlot, MethodSymbol method) { Debug.Assert(receiverSlot >= 0); do { var type = method.ContainingType; var notNullMembers = method.NotNullMembers; var notNullWhenTrueMembers = method.NotNullWhenTrueMembers; var notNullWhenFalseMembers = method.NotNullWhenFalseMembers; if (IsConditionalState) { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenFalse); } else { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref State); } if (method.ReturnType.SpecialType == SpecialType.System_Boolean && !(notNullWhenTrueMembers.IsEmpty && notNullWhenFalseMembers.IsEmpty)) { Split(); applyMemberPostConditions(receiverSlot, type, notNullWhenTrueMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullWhenFalseMembers, ref StateWhenFalse); } method = method.OverriddenMethod; } while (method != null); void applyMemberPostConditions(int receiverSlot, TypeSymbol type, ImmutableArray<string> members, ref LocalState state) { if (members.IsEmpty) { return; } foreach (var memberName in members) { markMembersAsNotNull(receiverSlot, type, memberName, ref state); } } void markMembersAsNotNull(int receiverSlot, TypeSymbol type, string memberName, ref LocalState state) { foreach (Symbol member in type.GetMembers(memberName)) { if (member.IsStatic) { receiverSlot = 0; } switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (GetOrCreateSlot(member, receiverSlot) is int memberSlot && memberSlot > 0) { state[memberSlot] = NullableFlowState.NotNull; } break; case SymbolKind.Event: case SymbolKind.Method: break; } } } } private ImmutableArray<VisitArgumentResult> VisitArgumentsEvaluate( ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<FlowAnalysisAnnotations> parameterAnnotationsOpt, BitVector defaultArguments) { Debug.Assert(!IsConditionalState); int n = arguments.Length; if (n == 0 && parameterAnnotationsOpt.IsDefaultOrEmpty) { return ImmutableArray<VisitArgumentResult>.Empty; } var resultsBuilder = ArrayBuilder<VisitArgumentResult>.GetInstance(n); var previousDisableDiagnostics = _disableDiagnostics; for (int i = 0; i < n; i++) { // we disable nullable warnings on default arguments _disableDiagnostics = defaultArguments[i] || previousDisableDiagnostics; resultsBuilder.Add(VisitArgumentEvaluate(arguments[i], GetRefKind(refKindsOpt, i), parameterAnnotationsOpt.IsDefault ? default : parameterAnnotationsOpt[i])); } _disableDiagnostics = previousDisableDiagnostics; SetInvalidResult(); return resultsBuilder.ToImmutableAndFree(); } private ImmutableArray<FlowAnalysisAnnotations> GetParametersAnnotations(ImmutableArray<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { ImmutableArray<FlowAnalysisAnnotations> parameterAnnotationsOpt = default; if (!parametersOpt.IsDefault) { parameterAnnotationsOpt = arguments.SelectAsArray( (argument, i, arg) => GetCorrespondingParameter(i, arg.parametersOpt, arg.argsToParamsOpt, arg.expanded).Annotations, (parametersOpt, argsToParamsOpt, expanded)); } return parameterAnnotationsOpt; } private VisitArgumentResult VisitArgumentEvaluate(BoundExpression argument, RefKind refKind, FlowAnalysisAnnotations annotations) { Debug.Assert(!IsConditionalState); var savedState = (argument.Kind == BoundKind.Lambda) ? this.State.Clone() : default(Optional<LocalState>); // Note: DoesNotReturnIf is ineffective on ref/out parameters switch (refKind) { case RefKind.Ref: Visit(argument); Unsplit(); break; case RefKind.None: case RefKind.In: switch (annotations & (FlowAnalysisAnnotations.DoesNotReturnIfTrue | FlowAnalysisAnnotations.DoesNotReturnIfFalse)) { case FlowAnalysisAnnotations.DoesNotReturnIfTrue: Visit(argument); if (IsConditionalState) { SetState(StateWhenFalse); } break; case FlowAnalysisAnnotations.DoesNotReturnIfFalse: Visit(argument); if (IsConditionalState) { SetState(StateWhenTrue); } break; default: VisitRvalue(argument); break; } break; case RefKind.Out: // As far as we can tell, there is no scenario relevant to nullability analysis // where splitting an L-value (for instance with a ref conditional) would affect the result. Visit(argument); // We'll want to use the l-value type, rather than the result type, for method re-inference UseLvalueOnly(argument); break; } Debug.Assert(!IsConditionalState); return new VisitArgumentResult(_visitResult, savedState); } /// <summary> /// Verifies that an argument's nullability is compatible with its parameter's on the way in. /// </summary> private void VisitArgumentConversionAndInboundAssignmentsAndPreConditions( BoundConversion? conversionOpt, BoundExpression argumentNoConversion, Conversion conversion, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, ArrayBuilder<VisitResult>? conversionResultsBuilder, bool extensionMethodThisArgument) { Debug.Assert(!this.IsConditionalState); // Note: we allow for some variance in `in` and `out` cases. Unlike in binding, we're not // limited by CLR constraints. var resultType = result.RValueType; switch (refKind) { case RefKind.None: case RefKind.In: { // Note: for lambda arguments, they will be converted in the context/state we saved for that argument if (conversion is { Kind: ConversionKind.ImplicitUserDefined }) { var argumentResultType = resultType.Type; conversion = GenerateConversion(_conversions, argumentNoConversion, argumentResultType, parameterType.Type, fromExplicitCast: false, extensionMethodThisArgument: false, isChecked: conversionOpt?.Checked ?? false); if (!conversion.Exists && !argumentNoConversion.IsSuppressed) { Debug.Assert(argumentResultType is not null); ReportNullabilityMismatchInArgument(argumentNoConversion.Syntax, argumentResultType, parameter, parameterType.Type, forOutput: false); } } var stateAfterConversion = VisitConversion( conversionOpt: conversionOpt, conversionOperand: argumentNoConversion, conversion: conversion, targetTypeWithNullability: ApplyLValueAnnotations(parameterType, parameterAnnotations), operandType: resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter, extensionMethodThisArgument: extensionMethodThisArgument, stateForLambda: result.StateForLambda, previousArgumentConversionResults: conversionResultsBuilder); // If the parameter has annotations, we perform an additional check for nullable value types if (CheckDisallowedNullAssignment(stateAfterConversion, parameterAnnotations, argumentNoConversion.Syntax.Location)) { LearnFromNonNullTest(argumentNoConversion, ref State); } SetResultType(argumentNoConversion, stateAfterConversion, updateAnalyzedNullability: false); conversionResultsBuilder?.Add(_visitResult); } break; case RefKind.Ref: if (!argumentNoConversion.IsSuppressed) { var lvalueResultType = result.LValueType; if (IsNullabilityMismatch(lvalueResultType.Type, parameterType.Type)) { // declared types must match, ignoring top-level nullability ReportNullabilityMismatchInRefArgument(argumentNoConversion, argumentType: lvalueResultType.Type, parameter, parameterType.Type); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(argumentNoConversion, ApplyLValueAnnotations(parameterType, parameterAnnotations), resultType, useLegacyWarnings: false); // If the parameter has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, argumentNoConversion.Syntax.Location); } } conversionResultsBuilder?.Add(result.VisitResult); break; case RefKind.Out: conversionResultsBuilder?.Add(result.VisitResult); break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } Debug.Assert(!this.IsConditionalState); } /// <summary>Returns <see langword="true"/> if this is an assignment forbidden by DisallowNullAttribute, otherwise <see langword="false"/>.</summary> private bool CheckDisallowedNullAssignment(TypeWithState state, FlowAnalysisAnnotations annotations, Location location, BoundExpression? boundValueOpt = null) { if (boundValueOpt is { WasCompilerGenerated: true }) { // We need to skip `return backingField;` in auto-prop getters return false; } // We do this extra check for types whose non-nullable version cannot be represented if (IsDisallowedNullAssignment(state, annotations)) { ReportDiagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, location); return true; } return false; } private static bool IsDisallowedNullAssignment(TypeWithState valueState, FlowAnalysisAnnotations targetAnnotations) { return ((targetAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) && hasNoNonNullableCounterpart(valueState.Type) && valueState.MayBeNull; static bool hasNoNonNullableCounterpart(TypeSymbol? type) { if (type is null) { return false; } // Some types that could receive a maybe-null value have a NotNull counterpart: // [NotNull]string? -> string // [NotNull]string -> string // [NotNull]TClass -> TClass // [NotNull]TClass? -> TClass // // While others don't: // [NotNull]int? -> X // [NotNull]TNullable -> X // [NotNull]TStruct? -> X // [NotNull]TOpen -> X return (type.Kind == SymbolKind.TypeParameter && !type.IsReferenceType) || type.IsNullableTypeOrTypeParameter(); } } /// <summary> /// Verifies that outbound assignments (from parameter to argument) are safe and /// tracks those assignments (or learns from post-condition attributes) /// </summary> private void VisitArgumentOutboundAssignmentsAndPostConditions( BoundExpression argument, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, CompareExchangeInfo compareExchangeInfoOpt) { // Note: the state may be conditional if a previous argument involved a conditional post-condition // The WhenTrue/False states correspond to the invocation returning true/false switch (refKind) { case RefKind.None: case RefKind.In: { // learn from post-conditions [Maybe/NotNull, Maybe/NotNullWhen] without using an assignment LearnFromPostConditions(argument, parameterAnnotations); } break; case RefKind.Ref: { // assign from a fictional value from the parameter to the argument. parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); if (!compareExchangeInfoOpt.IsDefault) { var adjustedState = LearnFromCompareExchangeMethod(in compareExchangeInfoOpt); parameterWithState = TypeWithState.Create(parameterType.Type, adjustedState); } var parameterValue = new BoundParameter(argument.Syntax, parameter); var lValueType = result.LValueType; trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // check whether parameter would unsafely let a null out in the worse case if (!argument.IsSuppressed) { var leftAnnotations = GetLValueAnnotations(argument); ReportNullableAssignmentIfNecessary( parameterValue, targetType: ApplyLValueAnnotations(lValueType, leftAnnotations), valueType: applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations), UseLegacyWarnings(argument, result.LValueType)); } } break; case RefKind.Out: { // compute the fictional parameter state parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); // Adjust parameter state if MaybeNull or MaybeNullWhen are present (for `var` type and for assignment warnings) var worstCaseParameterWithState = applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations); var declaredType = result.LValueType; var leftAnnotations = GetLValueAnnotations(argument); var lValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (argument is BoundLocal local && local.DeclarationKind == BoundLocalDeclarationKind.WithInferredType) { var varType = worstCaseParameterWithState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local.LocalSymbol, varType); lValueType = varType; } else if (argument is BoundDiscardExpression discard) { SetAnalyzedNullability(discard, new VisitResult(parameterWithState, parameterWithState.ToTypeWithAnnotations(compilation)), isLvalue: true); } // track state by assigning from a fictional value from the parameter to the argument. var parameterValue = new BoundParameter(argument.Syntax, parameter); // If the argument type has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(parameterWithState, leftAnnotations, argument.Syntax.Location); AdjustSetValue(argument, ref parameterWithState); trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // report warnings if parameter would unsafely let a null out in the worst case if (!argument.IsSuppressed) { ReportNullableAssignmentIfNecessary(parameterValue, lValueType, worstCaseParameterWithState, UseLegacyWarnings(argument, result.LValueType)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (!_conversions.HasIdentityOrImplicitReferenceConversion(parameterType.Type, lValueType.Type, ref discardedUseSiteInfo)) { ReportNullabilityMismatchInArgument(argument.Syntax, lValueType.Type, parameter, parameterType.Type, forOutput: true); } } } break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } FlowAnalysisAnnotations notNullBasedOnParameters(FlowAnalysisAnnotations parameterAnnotations, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, ParameterSymbol parameter) { if (!IsAnalyzingAttribute && notNullParametersOpt is object) { var notNullIfParameterNotNull = parameter.NotNullIfParameterNotNull; if (!notNullIfParameterNotNull.IsEmpty) { foreach (var notNullParameter in notNullParametersOpt) { if (notNullIfParameterNotNull.Contains(notNullParameter.Name)) { return FlowAnalysisAnnotations.NotNull; } } } } return parameterAnnotations; } void trackNullableStateForAssignment(BoundExpression parameterValue, TypeWithAnnotations lValueType, int targetSlot, TypeWithState parameterWithState, bool isSuppressed, FlowAnalysisAnnotations parameterAnnotations) { if (!IsConditionalState && !hasConditionalPostCondition(parameterAnnotations)) { TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, parameterWithState.WithSuppression(isSuppressed)); } else { Split(); var originalWhenFalse = StateWhenFalse.Clone(); SetState(StateWhenTrue); // Note: the suppression applies over the post-condition attributes TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenTrue(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); var newWhenTrue = State.Clone(); SetState(originalWhenFalse); TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenFalse(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); SetConditionalState(newWhenTrue, whenFalse: State); } } static bool hasConditionalPostCondition(FlowAnalysisAnnotations annotations) { return (((annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0)) || (((annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0)); } static TypeWithState applyPostConditionsUnconditionally(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNull return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenTrue(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && !(maybeNullWhenFalse && notNullWhenTrue)) { // [MaybeNull, NotNullWhen(true)] means [MaybeNullWhen(false)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenTrue) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenFalse(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenFalse && !(maybeNullWhenTrue && notNullWhenFalse)) { // [MaybeNull, NotNullWhen(false)] means [MaybeNullWhen(true)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenFalse) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } } /// <summary> /// Learn from postconditions on a by-value or 'in' argument. /// </summary> private void LearnFromPostConditions(BoundExpression argument, FlowAnalysisAnnotations parameterAnnotations) { // Note: NotNull = NotNullWhen(true) + NotNullWhen(false) bool notNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool notNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; // Note: MaybeNull = MaybeNullWhen(true) + MaybeNullWhen(false) bool maybeNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && maybeNullWhenFalse && !IsConditionalState && !(notNullWhenTrue && notNullWhenFalse)) { LearnFromNullTest(argument, ref State); } else if (notNullWhenTrue && notNullWhenFalse && !IsConditionalState && !(maybeNullWhenTrue || maybeNullWhenFalse)) { LearnFromNonNullTest(argument, ref State); } else if (notNullWhenTrue || notNullWhenFalse || maybeNullWhenTrue || maybeNullWhenFalse) { Split(); if (notNullWhenTrue) { LearnFromNonNullTest(argument, ref StateWhenTrue); } if (notNullWhenFalse) { LearnFromNonNullTest(argument, ref StateWhenFalse); } if (maybeNullWhenTrue) { LearnFromNullTest(argument, ref StateWhenTrue); } if (maybeNullWhenFalse) { LearnFromNullTest(argument, ref StateWhenFalse); } } } private (ImmutableArray<BoundExpression> arguments, ImmutableArray<Conversion> conversions) RemoveArgumentConversions( ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt) { int n = arguments.Length; var conversions = default(ImmutableArray<Conversion>); if (n > 0) { var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); var conversionsBuilder = ArrayBuilder<Conversion>.GetInstance(n); bool includedConversion = false; for (int i = 0; i < n; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); var argument = arguments[i]; var conversion = Conversion.Identity; if (refKind == RefKind.None) { var before = argument; (argument, conversion) = RemoveConversion(argument, includeExplicitConversions: false); if (argument != before) { SnapshotWalkerThroughConversionGroup(before, argument); includedConversion = true; } } argumentsBuilder.Add(argument); conversionsBuilder.Add(conversion); } if (includedConversion) { arguments = argumentsBuilder.ToImmutable(); conversions = conversionsBuilder.ToImmutable(); } argumentsBuilder.Free(); conversionsBuilder.Free(); } return (arguments, conversions); } private static VariableState GetVariableState(Variables variables, LocalState localState) { Debug.Assert(variables.Id == localState.Id); return new VariableState(variables.CreateSnapshot(), localState.CreateSnapshot()); } private (ParameterSymbol? Parameter, TypeWithAnnotations Type, FlowAnalysisAnnotations Annotations, bool isExpandedParamsArgument) GetCorrespondingParameter( int argumentOrdinal, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { if (parametersOpt.IsDefault) { return default; } var parameter = Binder.GetCorrespondingParameter(argumentOrdinal, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { Debug.Assert(!expanded); return default; } var type = parameter.TypeWithAnnotations; if (expanded && parameter.Ordinal == parametersOpt.Length - 1 && type.IsSZArray()) { type = ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations; return (parameter, type, FlowAnalysisAnnotations.None, isExpandedParamsArgument: true); } return (parameter, type, GetParameterAnnotations(parameter), isExpandedParamsArgument: false); } private MethodSymbol InferMethodTypeArguments( MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { Debug.Assert(method.IsGenericMethod); // https://github.com/dotnet/roslyn/issues/27961 OverloadResolution.IsMemberApplicableInNormalForm and // IsMemberApplicableInExpandedForm use the least overridden method. We need to do the same here. var definition = method.ConstructedFrom; var refKinds = ArrayBuilder<RefKind>.GetInstance(); if (argumentRefKindsOpt != null) { refKinds.AddRange(argumentRefKindsOpt); } // https://github.com/dotnet/roslyn/issues/27961 Do we really need OverloadResolution.GetEffectiveParameterTypes? // Aren't we doing roughly the same calculations in GetCorrespondingParameter? OverloadResolution.GetEffectiveParameterTypes( definition, arguments.Length, argsToParamsOpt, refKinds, isMethodGroupConversion: false, // https://github.com/dotnet/roslyn/issues/27961 `allowRefOmittedArguments` should be // false for constructors and several other cases (see Binder use). Should we // capture the original value in the BoundCall? allowRefOmittedArguments: true, binder: _binder, expanded: expanded, parameterTypes: out ImmutableArray<TypeWithAnnotations> parameterTypes, parameterRefKinds: out ImmutableArray<RefKind> parameterRefKinds); refKinds.Free(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var result = MethodTypeInferrer.Infer( _binder, _conversions, definition.TypeParameters, definition.ContainingType, parameterTypes, parameterRefKinds, arguments, ref discardedUseSiteInfo, new MethodInferenceExtensions(this)); if (!result.Success) { return method; } return definition.Construct(result.InferredTypeArguments); } private sealed class MethodInferenceExtensions : MethodTypeInferrer.Extensions { private readonly NullableWalker _walker; internal MethodInferenceExtensions(NullableWalker walker) { _walker = walker; } internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType(), GetNullableAnnotation(expr)); } /// <summary> /// Return top-level nullability for the expression. This method should be called on a limited /// set of expressions only. It should not be called on expressions tracked by flow analysis /// other than <see cref="BoundKind.ExpressionWithNullability"/> which is an expression /// specifically created in NullableWalker to represent the flow analysis state. /// </summary> private static NullableAnnotation GetNullableAnnotation(BoundExpression expr) { switch (expr.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.Literal: return expr.ConstantValue == ConstantValue.NotAvailable || !expr.ConstantValue.IsNull || expr.IsSuppressed ? NullableAnnotation.NotAnnotated : NullableAnnotation.Annotated; case BoundKind.ExpressionWithNullability: return ((BoundExpressionWithNullability)expr).NullableAnnotation; case BoundKind.MethodGroup: case BoundKind.UnboundLambda: case BoundKind.UnconvertedObjectCreationExpression: case BoundKind.ConvertedTupleLiteral: return NullableAnnotation.NotAnnotated; default: Debug.Assert(false); // unexpected value return NullableAnnotation.Oblivious; } } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { if (_walker.TryGetMethodGroupReceiverNullability(group.ReceiverOpt, out TypeWithState receiverType)) { if (!method.IsStatic) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } } return method.ReturnTypeWithAnnotations; } } private ImmutableArray<BoundExpression> GetArgumentsForMethodTypeInference(ImmutableArray<VisitArgumentResult> argumentResults, ImmutableArray<BoundExpression> arguments) { // https://github.com/dotnet/roslyn/issues/27961 MethodTypeInferrer.Infer relies // on the BoundExpressions for tuple element types and method groups. // By using a generic BoundValuePlaceholder, we're losing inference in those cases. // https://github.com/dotnet/roslyn/issues/27961 Inference should be based on // unconverted arguments. Consider cases such as `default`, lambdas, tuples. int n = argumentResults.Length; var builder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var visitArgumentResult = argumentResults[i]; var lambdaState = visitArgumentResult.StateForLambda; // Note: for `out` arguments, the argument result contains the declaration type (see `VisitArgumentEvaluate`) var argumentResult = visitArgumentResult.RValueType.ToTypeWithAnnotations(compilation); builder.Add(getArgumentForMethodTypeInference(arguments[i], argumentResult, lambdaState)); } return builder.ToImmutableAndFree(); BoundExpression getArgumentForMethodTypeInference(BoundExpression argument, TypeWithAnnotations argumentType, Optional<LocalState> lambdaState) { if (argument.Kind == BoundKind.Lambda) { Debug.Assert(lambdaState.HasValue); // MethodTypeInferrer must infer nullability for lambdas based on the nullability // from flow analysis rather than the declared nullability. To allow that, we need // to re-bind lambdas in MethodTypeInferrer. return getUnboundLambda((BoundLambda)argument, GetVariableState(_variables, lambdaState.Value)); } if (!argumentType.HasType) { return argument; } if (argument is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } || IsTargetTypedExpression(argument)) { // target-typed contexts don't contribute to nullability return new BoundExpressionWithNullability(argument.Syntax, argument, NullableAnnotation.Oblivious, type: null); } return new BoundExpressionWithNullability(argument.Syntax, argument, argumentType.NullableAnnotation, argumentType.Type); } static UnboundLambda getUnboundLambda(BoundLambda expr, VariableState variableState) { return expr.UnboundLambda.WithNullableState(variableState); } } private void CheckMethodConstraints(SyntaxNode syntax, MethodSymbol method) { if (_disableDiagnostics) { return; } var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); var nullabilityBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); ArrayBuilder<TypeParameterDiagnosticInfo>? useSiteDiagnosticsBuilder = null; ConstraintsHelper.CheckMethodConstraints( method, new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, NoLocation.Singleton, diagnostics: null, template: CompoundUseSiteInfo<AssemblySymbol>.Discarded), diagnosticsBuilder, nullabilityBuilder, ref useSiteDiagnosticsBuilder); foreach (var pair in nullabilityBuilder) { if (pair.UseSiteInfo.DiagnosticInfo is object) { Diagnostics.Add(pair.UseSiteInfo.DiagnosticInfo, syntax.Location); } } useSiteDiagnosticsBuilder?.Free(); nullabilityBuilder.Free(); diagnosticsBuilder.Free(); } /// <summary> /// Returns the expression without the top-most conversion plus the conversion. /// If the expression is not a conversion, returns the original expression plus /// the Identity conversion. If `includeExplicitConversions` is true, implicit and /// explicit conversions are considered. If `includeExplicitConversions` is false /// only implicit conversions are considered and if the expression is an explicit /// conversion, the expression is returned as is, with the Identity conversion. /// (Currently, the only visit method that passes `includeExplicitConversions: true` /// is VisitConversion. All other callers are handling implicit conversions only.) /// </summary> private static (BoundExpression expression, Conversion conversion) RemoveConversion(BoundExpression expr, bool includeExplicitConversions) { ConversionGroup? group = null; while (true) { if (expr.Kind != BoundKind.Conversion) { break; } var conversion = (BoundConversion)expr; if (group != conversion.ConversionGroupOpt && group != null) { // E.g.: (C)(B)a break; } group = conversion.ConversionGroupOpt; Debug.Assert(group != null || !conversion.ExplicitCastInCode); // Explicit conversions should include a group. if (!includeExplicitConversions && group?.IsExplicitConversion == true) { return (expr, Conversion.Identity); } expr = conversion.Operand; if (group == null) { // Ungrouped conversion should not be followed by another ungrouped // conversion. Otherwise, the conversions should have been grouped. // https://github.com/dotnet/roslyn/issues/34919 This assertion does not always hold true for // enum initializers //Debug.Assert(expr.Kind != BoundKind.Conversion || // ((BoundConversion)expr).ConversionGroupOpt != null || // ((BoundConversion)expr).ConversionKind == ConversionKind.NoConversion); return (expr, conversion.Conversion); } } return (expr, group?.Conversion ?? Conversion.Identity); } // See Binder.BindNullCoalescingOperator for initial binding. private Conversion GenerateConversionForConditionalOperator(BoundExpression sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool reportMismatch, bool isChecked) { var conversion = GenerateConversion(_conversions, sourceExpression, sourceType, destinationType, fromExplicitCast: false, extensionMethodThisArgument: false, isChecked: isChecked); bool canConvertNestedNullability = conversion.Exists; if (!canConvertNestedNullability && reportMismatch && !sourceExpression.IsSuppressed) { ReportNullabilityMismatchInAssignment(sourceExpression.Syntax, GetTypeAsDiagnosticArgument(sourceType), destinationType); } return conversion; } private static Conversion GenerateConversion(Conversions conversions, BoundExpression? sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool fromExplicitCast, bool extensionMethodThisArgument, bool isChecked) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool useExpression = sourceType is null || UseExpressionForConversion(sourceExpression); if (extensionMethodThisArgument) { return conversions.ClassifyImplicitExtensionMethodThisArgConversion( useExpression ? sourceExpression : null, sourceType, destinationType, ref discardedUseSiteInfo); } return useExpression ? (fromExplicitCast ? conversions.ClassifyConversionFromExpression(sourceExpression, destinationType, isChecked: isChecked, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromExpression(sourceExpression!, destinationType, ref discardedUseSiteInfo)) : (fromExplicitCast ? conversions.ClassifyConversionFromType(sourceType, destinationType, isChecked: isChecked, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromType(sourceType!, destinationType, ref discardedUseSiteInfo)); } /// <summary> /// Returns true if the expression should be used as the source when calculating /// a conversion from this expression, rather than using the type (with nullability) /// calculated by visiting this expression. Typically, that means expressions that /// do not have an explicit type but there are several other cases as well. /// (See expressions handled in ClassifyImplicitBuiltInConversionFromExpression.) /// </summary> private static bool UseExpressionForConversion([NotNullWhen(true)] BoundExpression? value) { if (value is null) { return false; } if (value.Type is null || value.Type.IsDynamic() || value.ConstantValue != null) { return true; } switch (value.Kind) { case BoundKind.InterpolatedString: return true; default: return false; } } /// <summary> /// Adjust declared type based on inferred nullability at the point of reference. /// </summary> private TypeWithState GetAdjustedResult(TypeWithState type, int slot) { if (this.State.HasValue(slot)) { NullableFlowState state = this.State[slot]; return TypeWithState.Create(type.Type, state); } return type; } /// <summary> /// Gets the corresponding member for a symbol from initial binding to match an updated receiver type in NullableWalker. /// For instance, this will map from List&lt;string~&gt;.Add(string~) to List&lt;string?&gt;.Add(string?) in the following example: /// <example> /// string s = null; /// var list = new[] { s }.ToList(); /// list.Add(null); /// </example> /// </summary> private static Symbol AsMemberOfType(TypeSymbol? type, Symbol symbol) { Debug.Assert((object)symbol != null); var containingType = type as NamedTypeSymbol; if (containingType is null || containingType.IsErrorType() || symbol is ErrorMethodSymbol) { return symbol; } if (symbol.Kind == SymbolKind.Method) { if (((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction) { // https://github.com/dotnet/roslyn/issues/27233 Handle type substitution for local functions. return symbol; } } if (symbol is TupleElementFieldSymbol or TupleErrorFieldSymbol) { return symbol.SymbolAsMember(containingType); } var symbolContainer = symbol.ContainingType; if (symbolContainer.IsAnonymousType) { int? memberIndex = symbol.Kind == SymbolKind.Property ? symbol.MemberIndexOpt : null; if (!memberIndex.HasValue) { return symbol; } return AnonymousTypeManager.GetAnonymousTypeProperty(containingType, memberIndex.GetValueOrDefault()); } if (!symbolContainer.IsGenericType) { Debug.Assert(symbol.ContainingType.IsDefinition); return symbol; } if (!containingType.IsGenericType) { return symbol; } if (symbolContainer.IsInterface) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } foreach (var @interface in containingType.AllInterfacesNoUseSiteDiagnostics) { if (tryAsMemberOfSingleType(@interface, out result)) { return result; } } } else { while (true) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } containingType = containingType.BaseTypeNoUseSiteDiagnostics; if ((object)containingType == null) { break; } } } Debug.Assert(false); // If this assert fails, add an appropriate test. return symbol; bool tryAsMemberOfSingleType(NamedTypeSymbol singleType, [NotNullWhen(true)] out Symbol? result) { if (!singleType.Equals(symbolContainer, TypeCompareKind.AllIgnoreOptions)) { result = null; return false; } var symbolDef = symbol.OriginalDefinition; result = symbolDef.SymbolAsMember(singleType); if (result is MethodSymbol resultMethod && resultMethod.IsGenericMethod) { result = resultMethod.Construct(((MethodSymbol)symbol).TypeArgumentsWithAnnotations); } return true; } } public override BoundNode? VisitConversion(BoundConversion node) { // https://github.com/dotnet/roslyn/issues/35732: Assert VisitConversion is only used for explicit conversions. //Debug.Assert(node.ExplicitCastInCode); //Debug.Assert(node.ConversionGroupOpt != null); //Debug.Assert(node.ConversionGroupOpt.ExplicitType.HasType); TypeWithAnnotations explicitType = node.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(node.Type); Debug.Assert(targetType.HasType); (BoundExpression operand, Conversion conversion) = RemoveConversion(node, includeExplicitConversions: true); SnapshotWalkerThroughConversionGroup(node, operand); TypeWithState operandType = VisitRvalueWithState(operand); SetResultType(node, VisitConversion( node, operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: fromExplicitCast, useLegacyWarnings: fromExplicitCast, AssignmentKind.Assignment, reportTopLevelWarnings: fromExplicitCast, reportRemainingWarnings: true, trackMembers: true)); return null; } /// <summary> /// Visit an expression. If an explicit target type is provided, the expression is converted /// to that type. This method should be called whenever an expression may contain /// an implicit conversion, even if that conversion was omitted from the bound tree, /// so the conversion can be re-classified with nullability. /// </summary> private TypeWithState VisitOptionalImplicitConversion(BoundExpression expr, TypeWithAnnotations targetTypeOpt, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind) { if (!targetTypeOpt.HasType) { return VisitRvalueWithState(expr); } var (resultType, completion) = VisitOptionalImplicitConversion(expr, targetTypeOpt, useLegacyWarnings, trackMembers, assignmentKind, delayCompletionForTargetType: false); Debug.Assert(completion is null); return resultType; } private (TypeWithState resultType, Func<TypeWithAnnotations, TypeWithState>? completion) VisitOptionalImplicitConversion( BoundExpression expr, TypeWithAnnotations targetTypeOpt, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind, bool delayCompletionForTargetType) { (BoundExpression operand, Conversion conversion) = RemoveConversion(expr, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(expr, operand); var operandType = VisitRvalueWithState(operand); return visitConversion(expr, targetTypeOpt, useLegacyWarnings, trackMembers, assignmentKind, operand, conversion, operandType, delayCompletionForTargetType); (TypeWithState resultType, Func<TypeWithAnnotations, TypeWithState>? completion) visitConversion( BoundExpression expr, TypeWithAnnotations targetTypeOpt, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind, BoundExpression operand, Conversion conversion, TypeWithState operandType, bool delayCompletionForTargetType) { if (delayCompletionForTargetType) { return (TypeWithState.Create(targetTypeOpt), visitConversionAsContinuation(expr, useLegacyWarnings, trackMembers, assignmentKind, operand, conversion, operandType)); } Debug.Assert(targetTypeOpt.HasType); // If an explicit conversion was used in place of an implicit conversion, the explicit // conversion was created by initial binding after reporting "error CS0266: // Cannot implicitly convert type '...' to '...'. An explicit conversion exists ...". // Since an error was reported, we don't need to report nested warnings as well. bool reportNestedWarnings = !conversion.IsExplicit; var resultType = VisitConversion( GetConversionIfApplicable(expr, operand), operand, conversion, targetTypeOpt, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: useLegacyWarnings, assignmentKind, reportTopLevelWarnings: true, reportRemainingWarnings: reportNestedWarnings, trackMembers: trackMembers); return (resultType, null); } Func<TypeWithAnnotations, TypeWithState> visitConversionAsContinuation(BoundExpression expr, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind, BoundExpression operand, Conversion conversion, TypeWithState operandType) { return (TypeWithAnnotations targetTypeOpt) => { var result = visitConversion(expr, targetTypeOpt, useLegacyWarnings, trackMembers, assignmentKind, operand, conversion, operandType, delayCompletionForTargetType: false); Debug.Assert(result.completion is null); return result.resultType; }; } } private static bool AreNullableAndUnderlyingTypes([NotNullWhen(true)] TypeSymbol? nullableTypeOpt, [NotNullWhen(true)] TypeSymbol? underlyingTypeOpt, out TypeWithAnnotations underlyingTypeWithAnnotations) { if (nullableTypeOpt?.IsNullableType() == true && underlyingTypeOpt?.IsNullableType() == false) { var typeArg = nullableTypeOpt.GetNullableUnderlyingTypeWithAnnotations(); if (typeArg.Type.Equals(underlyingTypeOpt, TypeCompareKind.AllIgnoreOptions)) { underlyingTypeWithAnnotations = typeArg; return true; } } underlyingTypeWithAnnotations = default; return false; } public override BoundNode? VisitTupleLiteral(BoundTupleLiteral node) { VisitTupleExpression(node); return null; } public override BoundNode? VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { Debug.Assert(!IsConditionalState); var savedState = this.State.Clone(); // Visit the source tuple so that the semantic model can correctly report nullability for it // Disable diagnostics, as we don't want to duplicate any that are produced by visiting the converted literal below VisitWithoutDiagnostics(node.SourceTuple); this.SetState(savedState); VisitTupleExpression(node); return null; } private void VisitTupleExpression(BoundTupleExpression node) { var arguments = node.Arguments; ImmutableArray<TypeWithState> elementTypes = arguments.SelectAsArray((a, w) => w.VisitRvalueWithState(a), this); ImmutableArray<TypeWithAnnotations> elementTypesWithAnnotations = elementTypes.SelectAsArray(a => a.ToTypeWithAnnotations(compilation)); var tupleOpt = (NamedTypeSymbol?)node.Type; if (tupleOpt is null) { SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); } else { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; TrackNullableStateOfTupleElements(slot, tupleOpt, arguments, elementTypes, argsToParamsOpt: default, useRestField: false); } tupleOpt = tupleOpt.WithElementTypes(elementTypesWithAnnotations); if (!_disableDiagnostics) { var locations = tupleOpt.TupleElements.SelectAsArray((element, location) => element.Locations.FirstOrDefault() ?? location, node.Syntax.Location); tupleOpt.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, node.Syntax.Location, diagnostics: null), typeSyntax: node.Syntax, locations, nullabilityDiagnosticsOpt: new BindingDiagnosticBag(Diagnostics)); } SetResultType(node, TypeWithState.Create(tupleOpt, NullableFlowState.NotNull)); } } /// <summary> /// Set the nullability of tuple elements for tuples at the point of construction. /// If <paramref name="useRestField"/> is true, the tuple was constructed with an explicit /// 'new ValueTuple' call, in which case the 8-th element, if any, represents the 'Rest' field. /// </summary> private void TrackNullableStateOfTupleElements( int slot, NamedTypeSymbol tupleType, ImmutableArray<BoundExpression> values, ImmutableArray<TypeWithState> types, ImmutableArray<int> argsToParamsOpt, bool useRestField) { Debug.Assert(tupleType.IsTupleType); Debug.Assert(values.Length == types.Length); Debug.Assert(values.Length == (useRestField ? Math.Min(tupleType.TupleElements.Length, NamedTypeSymbol.ValueTupleRestPosition) : tupleType.TupleElements.Length)); if (slot > 0) { var tupleElements = tupleType.TupleElements; int n = values.Length; if (useRestField) { n = Math.Min(n, NamedTypeSymbol.ValueTupleRestPosition - 1); } for (int i = 0; i < n; i++) { var argOrdinal = getArgumentOrdinalFromParameterOrdinal(i); trackState(values[argOrdinal], tupleElements[i], types[argOrdinal]); } if (useRestField && values.Length == NamedTypeSymbol.ValueTupleRestPosition && tupleType.GetMembers(NamedTypeSymbol.ValueTupleRestFieldName).FirstOrDefault() is FieldSymbol restField) { var argOrdinal = getArgumentOrdinalFromParameterOrdinal(NamedTypeSymbol.ValueTupleRestPosition - 1); trackState(values[argOrdinal], restField, types[argOrdinal]); } } void trackState(BoundExpression value, FieldSymbol field, TypeWithState valueType) { int targetSlot = GetOrCreateSlot(field, slot); TrackNullableStateForAssignment(value, field.TypeWithAnnotations, targetSlot, valueType, MakeSlot(value)); } int getArgumentOrdinalFromParameterOrdinal(int parameterOrdinal) { var index = argsToParamsOpt.IsDefault ? parameterOrdinal : argsToParamsOpt.IndexOf(parameterOrdinal); Debug.Assert(index != -1); return index; } } private void TrackNullableStateOfNullableValue(int containingSlot, TypeSymbol containingType, BoundExpression? value, TypeWithState valueType, int valueSlot) { Debug.Assert(containingType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T); Debug.Assert(containingSlot > 0); Debug.Assert(valueSlot > 0); int targetSlot = GetNullableOfTValueSlot(containingType, containingSlot, out Symbol? symbol); if (targetSlot > 0) { TrackNullableStateForAssignment(value, symbol!.GetTypeOrReturnType(), targetSlot, valueType, valueSlot); } } private void TrackNullableStateOfTupleConversion( BoundConversion? conversionOpt, BoundExpression convertedNode, Conversion conversion, TypeSymbol targetType, TypeSymbol operandType, int slot, int valueSlot, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings) { Debug.Assert(conversion.Kind == ConversionKind.ImplicitTuple || conversion.Kind == ConversionKind.ExplicitTuple); Debug.Assert(slot > 0); Debug.Assert(valueSlot > 0); var valueTuple = operandType as NamedTypeSymbol; if (valueTuple is null || !valueTuple.IsTupleType) { return; } var conversions = conversion.UnderlyingConversions; var targetElements = ((NamedTypeSymbol)targetType).TupleElements; var valueElements = valueTuple.TupleElements; int n = valueElements.Length; for (int i = 0; i < n; i++) { trackConvertedValue(targetElements[i], conversions[i], valueElements[i]); } void trackConvertedValue(FieldSymbol targetField, Conversion conversion, FieldSymbol valueField) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: case ConversionKind.Boxing: case ConversionKind.Unboxing: InheritNullableStateOfMember(slot, valueSlot, valueField, isDefaultValue: false, skipSlot: slot); break; case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, convertedNode, conversion, targetField.Type, valueField.Type, targetFieldSlot, valueFieldSlot, assignmentKind, parameterOpt, reportWarnings); } } } break; case ConversionKind.ImplicitNullable: case ConversionKind.ExplicitNullable: // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (AreNullableAndUnderlyingTypes(targetField.Type, valueField.Type, out _)) { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfNullableValue(targetFieldSlot, targetField.Type, null, valueField.TypeWithAnnotations.ToTypeWithState(), valueFieldSlot); } } } break; case ConversionKind.ImplicitUserDefined: case ConversionKind.ExplicitUserDefined: { var convertedType = VisitUserDefinedConversion( conversionOpt, convertedNode, conversion, targetField.TypeWithAnnotations, valueField.TypeWithAnnotations.ToTypeWithState(), useLegacyWarnings: false, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: reportWarnings, diagnosticLocation: (conversionOpt ?? convertedNode).Syntax.GetLocation()); int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = convertedType.State; } } break; default: break; } } } public override BoundNode? VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { base.VisitTupleBinaryOperator(node); SetNotNullResult(node); return null; } private void ReportNullabilityMismatchWithTargetDelegate(Location location, TypeSymbol targetType, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool invokedAsExtensionMethod) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, targetInvokeMethod, sourceInvokeMethod, new BindingDiagnosticBag(Diagnostics), reportBadDelegateReturn, reportBadDelegateParameter, extraArgument: (targetType, location), invokedAsExtensionMethod: invokedAsExtensionMethod); void reportBadDelegateReturn(BindingDiagnosticBag bag, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, arg.location, new FormattedSymbol(sourceInvokeMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), arg.targetType); } void reportBadDelegateParameter(BindingDiagnosticBag bag, MethodSymbol sourceInvokeMethod, MethodSymbol targetInvokeMethod, ParameterSymbol parameter, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, arg.location, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter), arg.targetType); } } private void ReportNullabilityMismatchWithTargetDelegate(Location location, NamedTypeSymbol delegateType, BoundLambda lambda) { MethodSymbol? targetInvokeMethod = delegateType.DelegateInvokeMethod; LambdaSymbol sourceMethod = lambda.Symbol; UnboundLambda unboundLambda = lambda.UnboundLambda; if (targetInvokeMethod is null || targetInvokeMethod.ParameterCount != sourceMethod.ParameterCount) { return; } // Parameter nullability is expected to match exactly. This corresponds to the behavior of initial binding. // Action<string> x = (object o) => { }; // error CS1661: Cannot convert lambda expression to delegate type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<object> y = (object? o) => { }; // warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'Action<object>'. // We check that by calling CheckValidNullableMethodOverride in both directions. // https://github.com/dotnet/roslyn/issues/35564: Consider relaxing and allow implicit conversions of nullability (as we do for method group conversions). if (lambda.Syntax is LambdaExpressionSyntax lambdaSyntax) { int start = lambdaSyntax.SpanStart; location = Location.Create(lambdaSyntax.SyntaxTree, new Text.TextSpan(start, lambdaSyntax.ArrowToken.Span.End - start)); } var diagnostics = new BindingDiagnosticBag(Diagnostics); if (SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, targetInvokeMethod, sourceMethod, diagnostics, reportBadDelegateReturn, reportBadDelegateParameter, extraArgument: location, invokedAsExtensionMethod: false)) { return; } SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, sourceMethod, targetInvokeMethod, diagnostics, reportBadDelegateReturn, reportBadDelegateParameter, extraArgument: location, invokedAsExtensionMethod: false); void reportBadDelegateReturn(BindingDiagnosticBag bag, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool topLevel, Location location) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, location, unboundLambda.MessageID.Localize(), delegateType); } void reportBadDelegateParameter(BindingDiagnosticBag bag, MethodSymbol sourceInvokeMethod, MethodSymbol targetInvokeMethod, ParameterSymbol parameterSymbol, bool topLevel, Location location) { // For anonymous functions with implicit parameters, no need to report this since the parameters can't be referenced if (unboundLambda.HasSignature) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, location, unboundLambda.ParameterName(parameterSymbol.Ordinal), unboundLambda.MessageID.Localize(), delegateType); } } } /// <summary> /// Gets the conversion node for passing to VisitConversion, if one should be passed. /// </summary> private static BoundConversion? GetConversionIfApplicable(BoundExpression? conversionOpt, BoundExpression convertedNode) { Debug.Assert(conversionOpt is null || convertedNode == conversionOpt // Note that convertedNode itself can be a BoundConversion, so we do this check explicitly // because the below calls to RemoveConversion could potentially strip that conversion. || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: false).expression || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: true).expression); return conversionOpt == convertedNode ? null : (BoundConversion?)conversionOpt; } /// <summary> /// Apply the conversion to the type of the operand and return the resulting type. /// If the operand does not have an explicit type, the operand expression is used. /// </summary> /// <param name="checkConversion"> /// If <see langword="true"/>, the incoming conversion is assumed to be from binding /// and will be re-calculated, this time considering nullability. /// Note that the conversion calculation considers nested nullability only. /// The caller is responsible for checking the top-level nullability of /// the type returned by this method. /// </param> /// <param name="trackMembers"> /// If <see langword="true"/>, the nullability of any members of the operand /// will be copied to the converted result when possible. /// </param> /// <param name="useLegacyWarnings"> /// If <see langword="true"/>, indicates that the "non-safety" diagnostic <see cref="ErrorCode.WRN_ConvertingNullableToNonNullable"/> /// should be given for an invalid conversion. /// </param> private TypeWithState VisitConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool checkConversion, bool fromExplicitCast, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt = null, bool reportTopLevelWarnings = true, bool reportRemainingWarnings = true, bool extensionMethodThisArgument = false, Optional<LocalState> stateForLambda = default, bool trackMembers = false, Location? diagnosticLocationOpt = null, ArrayBuilder<VisitResult>? previousArgumentConversionResults = null) { Debug.Assert(!trackMembers || !IsConditionalState); Debug.Assert(conversionOperand != null); if (IsTargetTypedExpression(conversionOperand)) { if (TargetTypedAnalysisCompletion.TryGetValue(conversionOperand, out Func<TypeWithAnnotations, TypeWithState>? completion)) { TargetTypedAnalysisCompletion.Remove(conversionOperand); #if DEBUG bool save_completingTargetTypedExpression = _completingTargetTypedExpression; _completingTargetTypedExpression = true; #endif if (conversionOperand is BoundObjectCreationExpressionBase && targetTypeWithNullability.IsNullableType()) { operandType = completion(targetTypeWithNullability.Type.GetNullableUnderlyingTypeWithAnnotations()); conversion = Conversion.MakeNullableConversion(ConversionKind.ImplicitNullable, Conversion.Identity); } else { operandType = completion(targetTypeWithNullability); } #if DEBUG _completingTargetTypedExpression = save_completingTargetTypedExpression; #endif } else { Debug.Assert(conversionOpt is null); } } NullableFlowState resultState = NullableFlowState.NotNull; bool canConvertNestedNullability = true; bool isSuppressed = false; diagnosticLocationOpt ??= (conversionOpt ?? conversionOperand).Syntax.GetLocation(); if (conversionOperand.IsSuppressed == true) { reportTopLevelWarnings = false; reportRemainingWarnings = false; isSuppressed = true; } #nullable disable TypeSymbol targetType = targetTypeWithNullability.Type; switch (conversion.Kind) { case ConversionKind.MethodGroup: { var group = conversionOperand as BoundMethodGroup; var (invokeSignature, parameters) = getDelegateOrFunctionPointerInfo(targetType); var method = conversion.Method; if (group != null) { if (method?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } method = CheckMethodGroupReceiverNullability(group, parameters, method, conversion.IsExtensionMethod); } if (reportRemainingWarnings && invokeSignature != null) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, targetType, invokeSignature, method, conversion.IsExtensionMethod); } } resultState = NullableFlowState.NotNull; break; static (MethodSymbol invokeSignature, ImmutableArray<ParameterSymbol>) getDelegateOrFunctionPointerInfo(TypeSymbol targetType) => targetType switch { NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { Parameters: { } parameters } signature } => (signature, parameters), FunctionPointerTypeSymbol { Signature: { Parameters: { } parameters } signature } => (signature, parameters), _ => (null, ImmutableArray<ParameterSymbol>.Empty), }; case ConversionKind.AnonymousFunction: if (conversionOperand is BoundLambda lambda) { var delegateType = targetType.GetDelegateType(); VisitLambda(lambda, delegateType, stateForLambda); if (reportRemainingWarnings) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, delegateType, lambda); } TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); return TypeWithState.Create(targetType, NullableFlowState.NotNull); } break; case ConversionKind.FunctionType: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedString: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedStringHandler: visitInterpolatedStringHandlerConstructor(); resultState = NullableFlowState.NotNull; break; case ConversionKind.ObjectCreation: case ConversionKind.SwitchExpression: case ConversionKind.ConditionalExpression: resultState = getConversionResultState(operandType); break; case ConversionKind.ExplicitUserDefined: case ConversionKind.ImplicitUserDefined: return VisitUserDefinedConversion(conversionOpt, conversionOperand, conversion, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt); case ConversionKind.ExplicitDynamic: case ConversionKind.ImplicitDynamic: resultState = getConversionResultState(operandType); break; case ConversionKind.Boxing: resultState = getBoxingConversionResultState(targetTypeWithNullability, operandType); break; case ConversionKind.Unboxing: if (targetType.IsNonNullableValueType()) { if (!operandType.IsNotNull && reportRemainingWarnings) { ReportDiagnostic(ErrorCode.WRN_UnboxPossibleNull, diagnosticLocationOpt); } LearnFromNonNullTest(conversionOperand, ref State); } else { resultState = getUnboxingConversionResultState(operandType); } break; case ConversionKind.ImplicitThrow: resultState = NullableFlowState.NotNull; break; case ConversionKind.NoConversion: resultState = getConversionResultState(operandType); break; case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: checkConversion = false; goto case ConversionKind.Identity; case ConversionKind.Identity: // If the operand is an explicit conversion, and this identity conversion // is converting to the same type including nullability, skip the conversion // to avoid reporting redundant warnings. Also check useLegacyWarnings // since that value was used when reporting warnings for the explicit cast. // Don't skip the node when it's a user-defined conversion, as identity conversions // on top of user-defined conversions means that we're coming in from VisitUserDefinedConversion // and that any warnings caught by this recursive call of VisitConversion won't be redundant. if (useLegacyWarnings && conversionOperand is BoundConversion operandConversion && !operandConversion.ConversionKind.IsUserDefinedConversion()) { var explicitType = operandConversion.ConversionGroupOpt?.ExplicitType; if (explicitType?.Equals(targetTypeWithNullability, TypeCompareKind.ConsiderEverything) == true) { TrackAnalyzedNullabilityThroughConversionGroup( calculateResultType(targetTypeWithNullability, fromExplicitCast, operandType.State, isSuppressed, targetType), conversionOpt, conversionOperand); return operandType; } } if (operandType.Type?.IsTupleType == true || conversionOperand.Kind == BoundKind.TupleLiteral) { goto case ConversionKind.ImplicitTuple; } goto case ConversionKind.ImplicitReference; case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: // Inherit state from the operand. if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument, isChecked: conversionOpt?.Checked ?? false); canConvertNestedNullability = conversion.Exists; } resultState = conversion.IsReference ? getReferenceConversionResultState(targetTypeWithNullability, operandType) : operandType.State; break; case ConversionKind.ImplicitNullable: if (trackMembers) { Debug.Assert(conversionOperand != null); if (AreNullableAndUnderlyingTypes(targetType, operandType.Type, out TypeWithAnnotations underlyingType)) { // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int containingSlot = GetOrCreatePlaceholderSlot(conversionOpt); Debug.Assert(containingSlot > 0); TrackNullableStateOfNullableValue(containingSlot, targetType, conversionOperand, underlyingType.ToTypeWithState(), valueSlot); } } } if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument, isChecked: conversionOpt?.Checked ?? false); canConvertNestedNullability = conversion.Exists; } resultState = operandType.State; break; case ConversionKind.ExplicitNullable: if (operandType.Type?.IsNullableType() == true && !targetType.IsNullableType()) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. if (reportTopLevelWarnings && operandType.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, diagnosticLocationOpt); } // Mark the value as not nullable, regardless of whether it was known to be nullable, // because the implied call to `.Value` will only succeed if not null. if (conversionOperand != null) { LearnFromNonNullTest(conversionOperand, ref State); } } goto case ConversionKind.ImplicitNullable; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ExplicitTuple: if (trackMembers) { Debug.Assert(conversionOperand != null); switch (conversion.Kind) { case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int slot = GetOrCreatePlaceholderSlot(conversionOpt); if (slot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, conversionOperand, conversion, targetType, operandType.Type, slot, valueSlot, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings); } } break; } } if (checkConversion && !targetType.IsErrorType()) { // https://github.com/dotnet/roslyn/issues/29699: Report warnings for user-defined conversions on tuple elements. conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument, isChecked: conversionOpt?.Checked ?? false); canConvertNestedNullability = conversion.Exists; } resultState = NullableFlowState.NotNull; break; case ConversionKind.Deconstruction: // Can reach here, with an error type, when the // Deconstruct method is missing or inaccessible. break; case ConversionKind.ExplicitEnumeration: // Can reach here, with an error type. break; default: Debug.Assert(targetType.IsValueType || targetType.IsErrorType()); break; } TypeWithState resultType = calculateResultType(targetTypeWithNullability, fromExplicitCast, resultState, isSuppressed, targetType); if (!conversionOperand.HasErrors && !targetType.IsErrorType()) { // Need to report all warnings that apply since the warnings can be suppressed individually. if (reportTopLevelWarnings) { ReportNullableAssignmentIfNecessary(conversionOperand, targetTypeWithNullability, resultType, useLegacyWarnings, assignmentKind, parameterOpt, diagnosticLocationOpt); } if (reportRemainingWarnings && !canConvertNestedNullability) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocationOpt, operandType.Type, parameterOpt, targetType, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocationOpt, GetTypeAsDiagnosticArgument(operandType.Type), targetType); } } } TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; #nullable enable static TypeWithState calculateResultType(TypeWithAnnotations targetTypeWithNullability, bool fromExplicitCast, NullableFlowState resultState, bool isSuppressed, TypeSymbol targetType) { if (isSuppressed) { resultState = NullableFlowState.NotNull; } else if (fromExplicitCast && targetTypeWithNullability.NullableAnnotation.IsAnnotated() && !targetType.IsNullableType()) { // An explicit cast to a nullable reference type introduces nullability resultState = targetType?.IsTypeParameterDisallowingAnnotationInCSharp8() == true ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } var resultType = TypeWithState.Create(targetType, resultState); return resultType; } static NullableFlowState getReferenceConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; switch (state) { case NullableFlowState.MaybeNull: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == true) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && dependsOnTypeParameter(typeParameter1, (TypeParameterSymbol)targetType.Type, NullableAnnotation.NotAnnotated, out var annotation)) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } break; case NullableFlowState.MaybeDefault: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == false) { return NullableFlowState.MaybeNull; } break; } return state; } // Converting to a less-derived type (object, interface, type parameter). // If the operand is MaybeNull, the result should be // MaybeNull (if the target type allows) or MaybeDefault otherwise. static NullableFlowState getBoxingConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && targetType.Type is TypeParameterSymbol typeParameter2) { bool dependsOn = dependsOnTypeParameter(typeParameter1, typeParameter2, NullableAnnotation.NotAnnotated, out var annotation); Debug.Assert(dependsOn); // If this case fails, add a corresponding test. if (dependsOn) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } return state; } // Converting to a more-derived type (struct, class, type parameter). // If the operand is MaybeNull or MaybeDefault, the result should be // MaybeDefault. static NullableFlowState getUnboxingConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } static NullableFlowState getConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } // If type parameter 1 depends on type parameter 2 (that is, if type parameter 2 appears // in the constraint types of type parameter 1), returns the effective annotation on // type parameter 2 in the constraints of type parameter 1. static bool dependsOnTypeParameter(TypeParameterSymbol typeParameter1, TypeParameterSymbol typeParameter2, NullableAnnotation typeParameter1Annotation, out NullableAnnotation annotation) { if (typeParameter1.Equals(typeParameter2, TypeCompareKind.AllIgnoreOptions)) { annotation = typeParameter1Annotation; return true; } bool dependsOn = false; var combinedAnnotation = NullableAnnotation.Annotated; foreach (var constraintType in typeParameter1.ConstraintTypesNoUseSiteDiagnostics) { if (constraintType.Type is TypeParameterSymbol constraintTypeParameter && dependsOnTypeParameter(constraintTypeParameter, typeParameter2, constraintType.NullableAnnotation, out var constraintAnnotation)) { dependsOn = true; combinedAnnotation = combinedAnnotation.Meet(constraintAnnotation); } } if (dependsOn) { annotation = combinedAnnotation.Join(typeParameter1Annotation); return true; } annotation = default; return false; } void visitInterpolatedStringHandlerConstructor() { var handlerData = conversionOperand.GetInterpolatedStringHandlerData(throwOnMissing: false); if (handlerData.IsDefault) { return; } if (previousArgumentConversionResults == null) { Debug.Assert(handlerData.ArgumentPlaceholders.IsEmpty || handlerData.ArgumentPlaceholders.Single().ArgumentIndex == BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter); visitHandlerConstruction(handlerData); return; } bool addedPlaceholders = false; foreach (var placeholder in handlerData.ArgumentPlaceholders) { switch (placeholder.ArgumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter: case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: // We presume that all instance parameters were dereferenced by calling the instance method this handler was passed to. This isn't strictly // true: the handler constructor will be run before the receiver is dereferenced. However, if the dereference isn't safe, that will be a // much better error to report than a mismatched argument nullability error. case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: break; default: if (previousArgumentConversionResults.Count > placeholder.ArgumentIndex) { // We intentionally do not give a replacement bound node for this placeholder, as we do not propagate any post conditions from the constructor // to the original location of the node. This is because the nullable walker is not a true evaluation-order walker, and doing so would cause // us to miss real warnings. AddPlaceholderReplacement(placeholder, expression: null, previousArgumentConversionResults[placeholder.ArgumentIndex]); addedPlaceholders = true; } break; } } visitHandlerConstruction(handlerData); if (addedPlaceholders) { foreach (var placeholder in handlerData.ArgumentPlaceholders) { if (placeholder.ArgumentIndex < previousArgumentConversionResults.Count && placeholder.ArgumentIndex >= 0) { RemovePlaceholderReplacement(placeholder); } } } } void visitHandlerConstruction(InterpolatedStringHandlerData handlerData) { #if DEBUG bool save_completingTargetTypedExpression = _completingTargetTypedExpression; _completingTargetTypedExpression = false; #endif VisitRvalue(handlerData.Construction); #if DEBUG _completingTargetTypedExpression = save_completingTargetTypedExpression; #endif } } private TypeWithState VisitUserDefinedConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportTopLevelWarnings, bool reportRemainingWarnings, Location diagnosticLocation) { Debug.Assert(!IsConditionalState); Debug.Assert(conversionOperand != null); Debug.Assert(targetTypeWithNullability.HasType); Debug.Assert(diagnosticLocation != null); Debug.Assert(conversion.Kind == ConversionKind.ExplicitUserDefined || conversion.Kind == ConversionKind.ImplicitUserDefined); TypeSymbol targetType = targetTypeWithNullability.Type; // cf. Binder.CreateUserDefinedConversion if (!conversion.IsValid) { var resultType = TypeWithState.Create(targetType, NullableFlowState.NotNull); TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; } // operand -> conversion "from" type // May be distinct from method parameter type for Nullable<T>. operandType = VisitConversion( conversionOpt, conversionOperand, conversion.UserDefinedFromConversion, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.FromType), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt: diagnosticLocation); // Update method based on operandType: see https://github.com/dotnet/roslyn/issues/29605. // (see NullableReferenceTypesTests.ImplicitConversions_07). var method = conversion.Method; Debug.Assert(method is object); Debug.Assert(method.ParameterCount == 1); Debug.Assert(operandType.Type is object); var parameter = method.Parameters[0]; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); TypeWithState underlyingOperandType = default; bool isLiftedConversion = false; if (operandType.Type.IsNullableType() && !parameterType.IsNullableType()) { var underlyingOperandTypeWithAnnotations = operandType.Type.GetNullableUnderlyingTypeWithAnnotations(); underlyingOperandType = underlyingOperandTypeWithAnnotations.ToTypeWithState(); isLiftedConversion = parameterType.Equals(underlyingOperandTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions); } // conversion "from" type -> method parameter type NullableFlowState operandState = operandType.State; Location operandLocation = conversionOperand.Syntax.GetLocation(); _ = ClassifyAndVisitConversion( conversionOperand, parameterType, isLiftedConversion ? underlyingOperandType : operandType, useLegacyWarnings, AssignmentKind.Argument, parameterOpt: parameter, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // in the case of a lifted conversion, we assume that the call to the operator occurs only if the argument is not-null if (!isLiftedConversion && CheckDisallowedNullAssignment(operandType, parameterAnnotations, conversionOperand.Syntax.Location)) { LearnFromNonNullTest(conversionOperand, ref State); } // method parameter type -> method return type var methodReturnType = method.ReturnTypeWithAnnotations; operandType = GetLiftedReturnTypeIfNecessary(isLiftedConversion, methodReturnType, operandState); if (!isLiftedConversion || operandState.IsNotNull()) { var returnNotNull = operandState.IsNotNull() && method.ReturnNotNullIfParameterNotNull.Contains(parameter.Name); if (returnNotNull) { operandType = operandType.WithNotNullState(); } else { operandType = ApplyUnconditionalAnnotations(operandType, GetRValueAnnotations(method)); } } // method return type -> conversion "to" type // May be distinct from method return type for Nullable<T>. operandType = ClassifyAndVisitConversion( conversionOperand, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.ToType), operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // conversion "to" type -> final type // We should only pass fromExplicitCast here. Given the following example: // // class A { public static explicit operator C(A a) => throw null!; } // class C // { // void M() => var c = (C?)new A(); // } // // This final conversion from the method return type "C" to the cast type "C?" is // where we will need to ensure that this is counted as an explicit cast, so that // the resulting operandType is nullable if that was introduced via cast. operandType = ClassifyAndVisitConversion( conversionOpt ?? conversionOperand, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: conversionOpt?.ExplicitCastInCode ?? false, diagnosticLocation); LearnFromPostConditions(conversionOperand, parameterAnnotations); TrackAnalyzedNullabilityThroughConversionGroup(operandType, conversionOpt, conversionOperand); return operandType; } private void SnapshotWalkerThroughConversionGroup(BoundExpression conversionExpression, BoundExpression convertedNode) { if (_snapshotBuilderOpt is null) { return; } var conversionOpt = conversionExpression as BoundConversion; var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode && conversionOpt.Syntax.SpanStart != convertedNode.Syntax.SpanStart) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); TakeIncrementalSnapshot(conversionOpt); conversionOpt = conversionOpt.Operand as BoundConversion; } } private void TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState resultType, BoundConversion? conversionOpt, BoundExpression convertedNode) { var visitResult = new VisitResult(resultType, resultType.ToTypeWithAnnotations(compilation)); var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); visitResult = withType(visitResult, conversionOpt.Type); SetAnalyzedNullability(conversionOpt, visitResult); conversionOpt = conversionOpt.Operand as BoundConversion; } static VisitResult withType(VisitResult visitResult, TypeSymbol newType) => new VisitResult(TypeWithState.Create(newType, visitResult.RValueType.State), TypeWithAnnotations.Create(newType, visitResult.LValueType.NullableAnnotation)); } /// <summary> /// Return the return type for a lifted operator, given the nullability state of its operands. /// </summary> private TypeWithState GetLiftedReturnType(TypeWithAnnotations returnType, NullableFlowState operandState) { bool typeNeedsLifting = returnType.Type.IsNonNullableValueType(); TypeSymbol type = typeNeedsLifting ? MakeNullableOf(returnType) : returnType.Type; NullableFlowState state = returnType.ToTypeWithState().State.Join(operandState); return TypeWithState.Create(type, state); } private static TypeWithState GetNullableUnderlyingTypeIfNecessary(bool isLifted, TypeWithState typeWithState) { if (isLifted) { var type = typeWithState.Type; if (type?.IsNullableType() == true) { return type.GetNullableUnderlyingTypeWithAnnotations().ToTypeWithState(); } } return typeWithState; } private TypeWithState GetLiftedReturnTypeIfNecessary(bool isLifted, TypeWithAnnotations returnType, NullableFlowState operandState) { return isLifted ? GetLiftedReturnType(returnType, operandState) : returnType.ToTypeWithState(); } private TypeSymbol MakeNullableOf(TypeWithAnnotations underlying) { return compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(ImmutableArray.Create(underlying)); } private TypeWithState ClassifyAndVisitConversion( BoundExpression node, TypeWithAnnotations targetType, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings, bool fromExplicitCast, Location diagnosticLocation) { Debug.Assert(operandType.Type is object); Debug.Assert(diagnosticLocation != null); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyStandardConversion(operandType.Type, targetType.Type, ref discardedUseSiteInfo); if (reportWarnings && !conversion.Exists) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocation, operandType.Type, parameterOpt, targetType.Type, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocation, operandType.Type, targetType.Type); } } return VisitConversion( conversionOpt: null, conversionOperand: node, conversion, targetType, operandType, checkConversion: false, fromExplicitCast, useLegacyWarnings: useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: !fromExplicitCast && reportWarnings, diagnosticLocationOpt: diagnosticLocation); } public override BoundNode? VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { Debug.Assert(node.Type.IsDelegateType()); if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } Action<NamedTypeSymbol>? analysisCompletion; var delegateType = (NamedTypeSymbol)node.Type; switch (node.Argument) { case BoundMethodGroup group: { analysisCompletion = visitMethodGroupArgument(node, delegateType, group); } break; case BoundLambda lambda: { analysisCompletion = visitLambdaArgument(delegateType, lambda, node.WasTargetTyped); } break; case BoundExpression arg when arg.Type is { TypeKind: TypeKind.Delegate }: { analysisCompletion = visitDelegateArgument(delegateType, arg, node.WasTargetTyped); } break; default: VisitRvalue(node.Argument); analysisCompletion = null; break; } TypeWithState result = setAnalyzedNullability(node, delegateType, analysisCompletion, node.WasTargetTyped); SetResultType(node, result, updateAnalyzedNullability: false); return null; TypeWithState setAnalyzedNullability(BoundDelegateCreationExpression node, NamedTypeSymbol delegateType, Action<NamedTypeSymbol>? analysisCompletion, bool isTargetTyped) { var result = TypeWithState.Create(delegateType, NullableFlowState.NotNull); if (isTargetTyped) { setAnalyzedNullabilityAsContinuation(node, analysisCompletion); } else { Debug.Assert(analysisCompletion is null); SetAnalyzedNullability(node, result); } return result; } void setAnalyzedNullabilityAsContinuation(BoundDelegateCreationExpression node, Action<NamedTypeSymbol>? analysisCompletion) { TargetTypedAnalysisCompletion[node] = (TypeWithAnnotations resultTypeWithAnnotations) => { Debug.Assert(TypeSymbol.Equals(resultTypeWithAnnotations.Type, node.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); var delegateType = (NamedTypeSymbol)resultTypeWithAnnotations.Type; analysisCompletion?.Invoke(delegateType); return setAnalyzedNullability(node, delegateType, analysisCompletion: null, isTargetTyped: false); }; } Action<NamedTypeSymbol>? visitMethodGroupArgument(BoundDelegateCreationExpression node, NamedTypeSymbol delegateType, BoundMethodGroup group) { VisitMethodGroup(group); SetAnalyzedNullability(group, default); return analyzeMethodGroupConversion(node, delegateType, group, node.WasTargetTyped); } Action<NamedTypeSymbol>? analyzeMethodGroupConversion(BoundDelegateCreationExpression node, NamedTypeSymbol delegateType, BoundMethodGroup group, bool isTargetTyped) { if (isTargetTyped) { return analyzeMethodGroupConversionAsContinuation(node, group); } var method = node.MethodOpt; if (method is object && delegateType.DelegateInvokeMethod is { } delegateInvokeMethod) { method = CheckMethodGroupReceiverNullability(group, delegateInvokeMethod.Parameters, method, node.IsExtensionMethod); if (!group.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(group.Syntax.Location, delegateType, delegateInvokeMethod, method, node.IsExtensionMethod); } } return null; } Action<NamedTypeSymbol>? analyzeMethodGroupConversionAsContinuation(BoundDelegateCreationExpression node, BoundMethodGroup group) { return (NamedTypeSymbol delegateType) => { analyzeMethodGroupConversion(node, delegateType, group, isTargetTyped: false); }; } Action<NamedTypeSymbol>? visitLambdaArgument(NamedTypeSymbol delegateType, BoundLambda lambda, bool isTargetTyped) { SetNotNullResult(lambda); return analyzeLambdaConversion(delegateType, lambda, isTargetTyped); } Action<NamedTypeSymbol>? analyzeLambdaConversion(NamedTypeSymbol delegateType, BoundLambda lambda, bool isTargetTyped) { if (isTargetTyped) { return analyzeLambdaConversionAsContinuation(lambda); } VisitLambda(lambda, delegateType); if (!lambda.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(lambda.Symbol.DiagnosticLocation, delegateType, lambda); } return null; } Action<NamedTypeSymbol> analyzeLambdaConversionAsContinuation(BoundLambda lambda) { return (NamedTypeSymbol delegateType) => analyzeLambdaConversion(delegateType, lambda, isTargetTyped: false); } Action<NamedTypeSymbol>? visitDelegateArgument(NamedTypeSymbol delegateType, BoundExpression arg, bool isTargetTyped) { Debug.Assert(arg.Type is not null); TypeSymbol argType = arg.Type; var argTypeWithAnnotations = TypeWithAnnotations.Create(argType, NullableAnnotation.NotAnnotated); var argState = VisitRvalueWithState(arg); ReportNullableAssignmentIfNecessary(arg, argTypeWithAnnotations, argState, useLegacyWarnings: false); // Delegate creation will throw an exception if the argument is null LearnFromNonNullTest(arg, ref State); return analyzeDelegateConversion(delegateType, arg, isTargetTyped); } Action<NamedTypeSymbol>? analyzeDelegateConversion(NamedTypeSymbol delegateType, BoundExpression arg, bool isTargetTyped) { if (isTargetTyped) { return analyzeDelegateConversionAsContinuation(arg); } Debug.Assert(arg.Type is not null); TypeSymbol argType = arg.Type; if (!arg.IsSuppressed && delegateType.DelegateInvokeMethod is { } delegateInvokeMethod && argType.DelegateInvokeMethod() is { } argInvokeMethod) { ReportNullabilityMismatchWithTargetDelegate(arg.Syntax.Location, delegateType, delegateInvokeMethod, argInvokeMethod, invokedAsExtensionMethod: false); } return null; } Action<NamedTypeSymbol> analyzeDelegateConversionAsContinuation(BoundExpression arg) { return (NamedTypeSymbol delegateType) => analyzeDelegateConversion(delegateType, arg, isTargetTyped: false); } } public override BoundNode? VisitMethodGroup(BoundMethodGroup node) { Debug.Assert(!IsConditionalState); var receiverOpt = node.ReceiverOpt; if (receiverOpt != null) { VisitRvalue(receiverOpt); // Receiver nullability is checked when applying the method group conversion, // when we have a specific method, to avoid reporting null receiver warnings // for extension method delegates. Here, store the receiver state for that check. SetMethodGroupReceiverNullability(receiverOpt, ResultType); } SetNotNullResult(node); return null; } private bool TryGetMethodGroupReceiverNullability([NotNullWhen(true)] BoundExpression? receiverOpt, out TypeWithState type) { if (receiverOpt != null && _methodGroupReceiverMapOpt != null && _methodGroupReceiverMapOpt.TryGetValue(receiverOpt, out type)) { return true; } else { type = default; return false; } } private void SetMethodGroupReceiverNullability(BoundExpression receiver, TypeWithState type) { _methodGroupReceiverMapOpt ??= PooledDictionary<BoundExpression, TypeWithState>.GetInstance(); _methodGroupReceiverMapOpt[receiver] = type; } private MethodSymbol CheckMethodGroupReceiverNullability(BoundMethodGroup group, ImmutableArray<ParameterSymbol> parameters, MethodSymbol method, bool invokedAsExtensionMethod) { var receiverOpt = group.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { var syntax = group.Syntax; if (!invokedAsExtensionMethod) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } if (method.IsGenericMethod && HasImplicitTypeArguments(group.Syntax)) { var arguments = ArrayBuilder<BoundExpression>.GetInstance(); if (invokedAsExtensionMethod) { arguments.Add(CreatePlaceholderIfNecessary(receiverOpt, receiverType.ToTypeWithAnnotations(compilation))); } // Create placeholders for the arguments. (See Conversions.GetDelegateArguments() // which is used for that purpose in initial binding.) foreach (var parameter in parameters) { var parameterType = parameter.TypeWithAnnotations; arguments.Add(new BoundExpressionWithNullability(syntax, new BoundParameter(syntax, parameter), parameterType.NullableAnnotation, parameterType.Type)); } Debug.Assert(_binder is object); method = InferMethodTypeArguments(method, arguments.ToImmutableAndFree(), argumentRefKindsOpt: default, argsToParamsOpt: default, expanded: false); } if (invokedAsExtensionMethod) { CheckExtensionMethodThisNullability(receiverOpt, Conversion.Identity, method.Parameters[0], receiverType); } else { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } if (ConstraintsHelper.RequiresChecking(method)) { CheckMethodConstraints(syntax, method); } } return method; } public override BoundNode? VisitLambda(BoundLambda node) { // Note: actual lambda analysis happens after this call (primarily in VisitConversion). // Here we just indicate that a lambda expression produces a non-null value. SetNotNullResult(node); return null; } private void VisitLambda(BoundLambda node, NamedTypeSymbol? delegateTypeOpt, Optional<LocalState> initialState = default) { Debug.Assert(delegateTypeOpt?.IsDelegateType() != false); var delegateInvokeMethod = delegateTypeOpt?.DelegateInvokeMethod; UseDelegateInvokeParameterAndReturnTypes(node, delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); if (useDelegateInvokeParameterTypes && _snapshotBuilderOpt is object) { SetUpdatedSymbol(node, node.Symbol, delegateTypeOpt!); } AnalyzeLocalFunctionOrLambda( node, node.Symbol, initialState.HasValue ? initialState.Value : State.Clone(), delegateInvokeMethod, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType); } private static void UseDelegateInvokeParameterAndReturnTypes(BoundLambda lambda, MethodSymbol? delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType) { if (delegateInvokeMethod is null) { useDelegateInvokeParameterTypes = false; useDelegateInvokeReturnType = false; } else { var unboundLambda = lambda.UnboundLambda; useDelegateInvokeParameterTypes = !unboundLambda.HasExplicitlyTypedParameterList; useDelegateInvokeReturnType = !unboundLambda.HasExplicitReturnType(out _, out _); } } public override BoundNode? VisitUnboundLambda(UnboundLambda node) { // The presence of this node suggests an error was detected in an earlier phase. // Analyze the body to report any additional warnings. var lambda = node.BindForErrorRecovery(); VisitLambda(lambda, delegateTypeOpt: null); SetNotNullResult(node); return null; } public override BoundNode? VisitThisReference(BoundThisReference node) { VisitThisOrBaseReference(node); return null; } private void VisitThisOrBaseReference(BoundExpression node) { var rvalueResult = TypeWithState.Create(node.Type, NullableFlowState.NotNull); var lvalueResult = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); SetResult(node, rvalueResult, lvalueResult); } public override BoundNode? VisitParameter(BoundParameter node) { var parameter = node.ParameterSymbol; int slot = GetOrCreateSlot(parameter); var parameterType = GetDeclaredParameterResult(parameter); var typeWithState = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations); SetResult(node, GetAdjustedResult(typeWithState, slot), parameterType); return null; } public override BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) { Debug.Assert(!IsConditionalState); var left = node.Left; switch (left) { // when binding initializers, we treat assignments to auto-properties or field-like events as direct assignments to the underlying field. // in order to track member state based on these initializers, we need to see the assignment in terms of the associated member case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: PropertySymbol autoProperty } } fieldAccess: left = new BoundPropertyAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, autoProperty, LookupResultKind.Viable, autoProperty.Type, fieldAccess.HasErrors); break; case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: EventSymbol @event } } fieldAccess: left = new BoundEventAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, @event, isUsableAsField: true, LookupResultKind.Viable, @event.Type, fieldAccess.HasErrors); break; } var right = node.Right; VisitLValue(left); // we may enter a conditional state for error scenarios on the LHS. Unsplit(); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (left.Kind == BoundKind.EventAccess && ((BoundEventAccess)left).EventSymbol.IsWindowsRuntimeEvent) { // Event assignment is a call to an Add method. (Note that assignment // of non-field-like events uses BoundEventAssignmentOperator // rather than BoundAssignmentOperator.) VisitRvalue(right); SetNotNullResult(node); } else { TypeWithState rightState; if (!node.IsRef) { var discarded = left is BoundDiscardExpression; rightState = VisitOptionalImplicitConversion(right, targetTypeOpt: discarded ? default : leftLValueType, UseLegacyWarnings(left, leftLValueType), trackMembers: true, AssignmentKind.Assignment); Unsplit(); } else { rightState = VisitRefExpression(right, leftLValueType); } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(rightState, leftAnnotations, right.Syntax.Location); AdjustSetValue(left, ref rightState); TrackNullableStateForAssignment(right, leftLValueType, MakeSlot(left), rightState, MakeSlot(right)); if (left is BoundDiscardExpression) { var lvalueType = rightState.ToTypeWithAnnotations(compilation); SetResult(left, rightState, lvalueType, isLvalue: true); SetResult(node, rightState, lvalueType); } else { SetResult(node, TypeWithState.Create(leftLValueType.Type, rightState.State), leftLValueType); } } return null; } private bool IsPropertyOutputMoreStrictThanInput(PropertySymbol property) { var type = property.TypeWithAnnotations; var annotations = IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : property.GetFlowAnalysisAnnotations(); var lValueType = ApplyLValueAnnotations(type, annotations); if (lValueType.NullableAnnotation.IsOblivious() || !lValueType.CanBeAssignedNull) { return false; } var rValueType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), annotations); return rValueType.IsNotNull; } /// <summary> /// When the allowed output of a property/indexer is not-null but the allowed input is maybe-null, we store a not-null value instead. /// This way, assignment of a legal input value results in a legal output value. /// This adjustment doesn't apply to oblivious properties/indexers. /// </summary> private void AdjustSetValue(BoundExpression left, ref TypeWithState rightState) { var property = left switch { BoundPropertyAccess propAccess => propAccess.PropertySymbol, BoundIndexerAccess indexerAccess => indexerAccess.Indexer, _ => null }; if (property is not null && IsPropertyOutputMoreStrictThanInput(property)) { rightState = rightState.WithNotNullState(); } } private FlowAnalysisAnnotations GetLValueAnnotations(BoundExpression expr) { Debug.Assert(expr is not BoundObjectInitializerMember); // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = expr switch { BoundPropertyAccess property => property.PropertySymbol.GetFlowAnalysisAnnotations(), BoundIndexerAccess indexer => indexer.Indexer.GetFlowAnalysisAnnotations(), BoundFieldAccess field => GetFieldAnnotations(field.FieldSymbol), BoundParameter { ParameterSymbol: ParameterSymbol parameter } => ToInwardAnnotations(GetParameterAnnotations(parameter) & ~FlowAnalysisAnnotations.NotNull), // NotNull is enforced upon method exit _ => FlowAnalysisAnnotations.None }; return annotations & (FlowAnalysisAnnotations.DisallowNull | FlowAnalysisAnnotations.AllowNull); } private static FlowAnalysisAnnotations GetFieldAnnotations(FieldSymbol field) { return field.AssociatedSymbol is PropertySymbol property ? property.GetFlowAnalysisAnnotations() : field.FlowAnalysisAnnotations; } private FlowAnalysisAnnotations GetObjectInitializerMemberLValueAnnotations(Symbol memberSymbol) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = memberSymbol switch { PropertySymbol prop => prop.GetFlowAnalysisAnnotations(), FieldSymbol field => GetFieldAnnotations(field), _ => FlowAnalysisAnnotations.None }; return annotations & (FlowAnalysisAnnotations.DisallowNull | FlowAnalysisAnnotations.AllowNull); } private static FlowAnalysisAnnotations ToInwardAnnotations(FlowAnalysisAnnotations outwardAnnotations) { var annotations = FlowAnalysisAnnotations.None; if ((outwardAnnotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen count as MaybeNull annotations |= FlowAnalysisAnnotations.AllowNull; } if ((outwardAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNullWhenTrue and NotNullWhenFalse don't count on their own. Only NotNull (ie. both flags) matters. annotations |= FlowAnalysisAnnotations.DisallowNull; } return annotations; } private static bool UseLegacyWarnings(BoundExpression expr, TypeWithAnnotations exprType) { switch (expr.Kind) { case BoundKind.Local: return expr.GetRefKind() == RefKind.None; case BoundKind.Parameter: RefKind kind = ((BoundParameter)expr).ParameterSymbol.RefKind; return kind == RefKind.None; default: return false; } } public override BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { return VisitDeconstructionAssignmentOperator(node, rightResultOpt: null); } private BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node, TypeWithState? rightResultOpt) { var previousDisableNullabilityAnalysis = _disableNullabilityAnalysis; _disableNullabilityAnalysis = true; var left = node.Left; var right = node.Right; var variables = GetDeconstructionAssignmentVariables(left); if (node.HasErrors) { // In the case of errors, simply visit the right as an r-value to update // any nullability state even though deconstruction is skipped. VisitRvalue(right.Operand); } else { VisitDeconstructionArguments(variables, right.Conversion, right.Operand, rightResultOpt); } variables.FreeAll(v => v.NestedVariables); // https://github.com/dotnet/roslyn/issues/33011: Result type should be inferred and the constraints should // be re-verified. Even though the standard tuple type has no constraints we support that scenario. Constraints_78 // has a test for this case that should start failing when this is fixed. SetNotNullResult(node); _disableNullabilityAnalysis = previousDisableNullabilityAnalysis; return null; } private void VisitDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt = null) { Debug.Assert(conversion.Kind == ConversionKind.Deconstruction); if (!conversion.DeconstructionInfo.IsDefault) { VisitDeconstructMethodArguments(variables, conversion, right, rightResultOpt); } else { VisitTupleDeconstructionArguments(variables, conversion.DeconstructConversionInfo, right, rightResultOpt); } } private void VisitDeconstructMethodArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt) { VisitRvalue(right); // If we were passed an explicit right result, use that rather than the visited result if (rightResultOpt.HasValue) { SetResultType(right, rightResultOpt.Value); } var rightResult = ResultType; var invocation = conversion.DeconstructionInfo.Invocation as BoundCall; var deconstructMethod = invocation?.Method; if (deconstructMethod is object) { Debug.Assert(invocation is object); Debug.Assert(rightResult.Type is object); int n = variables.Count; if (!invocation.InvokedAsExtensionMethod) { _ = CheckPossibleNullReceiver(right); // update the deconstruct method with any inferred type parameters of the containing type if (deconstructMethod.OriginalDefinition != deconstructMethod) { deconstructMethod = (MethodSymbol)AsMemberOfType(rightResult.Type, deconstructMethod); } } else { if (deconstructMethod.IsGenericMethod) { // re-infer the deconstruct parameters based on the 'this' parameter ArrayBuilder<BoundExpression> placeholderArgs = ArrayBuilder<BoundExpression>.GetInstance(n + 1); placeholderArgs.Add(CreatePlaceholderIfNecessary(right, rightResult.ToTypeWithAnnotations(compilation))); for (int i = 0; i < n; i++) { placeholderArgs.Add(new BoundExpressionWithNullability(variables[i].Expression.Syntax, variables[i].Expression, NullableAnnotation.Oblivious, conversion.DeconstructionInfo.OutputPlaceholders[i].Type)); } deconstructMethod = InferMethodTypeArguments(deconstructMethod, placeholderArgs.ToImmutableAndFree(), invocation.ArgumentRefKindsOpt, invocation.ArgsToParamsOpt, invocation.Expanded); // check the constraints remain valid with the re-inferred parameter types if (ConstraintsHelper.RequiresChecking(deconstructMethod)) { CheckMethodConstraints(invocation.Syntax, deconstructMethod); } } } var parameters = deconstructMethod.Parameters; int offset = invocation.InvokedAsExtensionMethod ? 1 : 0; Debug.Assert(parameters.Length - offset == n); if (invocation.InvokedAsExtensionMethod) { // Check nullability for `this` parameter var argConversion = RemoveConversion(invocation.Arguments[0], includeExplicitConversions: false).conversion; CheckExtensionMethodThisNullability(right, argConversion, deconstructMethod.Parameters[0], rightResult); } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var (placeholder, placeholderConversion) = conversion.DeconstructConversionInfo[i]; var underlyingConversion = BoundNode.GetConversion(placeholderConversion, placeholder); var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { var nestedRight = CreatePlaceholderIfNecessary(invocation.Arguments[i + offset], parameter.TypeWithAnnotations); VisitDeconstructionArguments(nestedVariables, underlyingConversion, right: nestedRight); } else { VisitArgumentConversionAndInboundAssignmentsAndPreConditions(conversionOpt: null, variable.Expression, underlyingConversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), conversionResultsBuilder: null, extensionMethodThisArgument: false); } } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var nestedVariables = variable.NestedVariables; if (nestedVariables == null) { VisitArgumentOutboundAssignmentsAndPostConditions( variable.Expression, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetRValueAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), notNullParametersOpt: null, compareExchangeInfoOpt: default); } } } } private void VisitTupleDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, ImmutableArray<(BoundValuePlaceholder? placeholder, BoundExpression? conversion)> deconstructConversionInfo, BoundExpression right, TypeWithState? rightResultOpt) { int n = variables.Count; var rightParts = GetDeconstructionRightParts(right, rightResultOpt); Debug.Assert(rightParts.Length == n); for (int i = 0; i < n; i++) { var variable = variables[i]; var (placeholder, placeholderConversion) = deconstructConversionInfo[i]; var underlyingConversion = BoundNode.GetConversion(placeholderConversion, placeholder); var rightPart = rightParts[i]; var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { VisitDeconstructionArguments(nestedVariables, underlyingConversion, rightPart); } else { var lvalueType = variable.Type; var leftAnnotations = GetLValueAnnotations(variable.Expression); lvalueType = ApplyLValueAnnotations(lvalueType, leftAnnotations); TypeWithState operandType; TypeWithState valueType; int valueSlot; if (underlyingConversion.IsIdentity) { if (variable.Expression is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } local) { // when the LHS is a var declaration, we can just visit the right part to infer the type valueType = operandType = VisitRvalueWithState(rightPart); _variables.SetType(local.LocalSymbol, operandType.ToAnnotatedTypeWithAnnotations(compilation)); } else { operandType = default; valueType = VisitOptionalImplicitConversion(rightPart, lvalueType, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); Unsplit(); } valueSlot = MakeSlot(rightPart); } else { operandType = VisitRvalueWithState(rightPart); valueType = VisitConversion( conversionOpt: null, rightPart, underlyingConversion, lvalueType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: true, AssignmentKind.Assignment, reportTopLevelWarnings: true, reportRemainingWarnings: true, trackMembers: false); valueSlot = -1; } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(valueType, leftAnnotations, right.Syntax.Location); int targetSlot = MakeSlot(variable.Expression); AdjustSetValue(variable.Expression, ref valueType); TrackNullableStateForAssignment(rightPart, lvalueType, targetSlot, valueType, valueSlot); // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (targetSlot > 0 && underlyingConversion.Kind == ConversionKind.ImplicitNullable && AreNullableAndUnderlyingTypes(lvalueType.Type, operandType.Type, out TypeWithAnnotations underlyingType)) { valueSlot = MakeSlot(rightPart); if (valueSlot > 0) { var valueBeforeNullableWrapping = TypeWithState.Create(underlyingType.Type, NullableFlowState.NotNull); TrackNullableStateOfNullableValue(targetSlot, lvalueType.Type, rightPart, valueBeforeNullableWrapping, valueSlot); } } } } } private readonly struct DeconstructionVariable { internal readonly BoundExpression Expression; internal readonly TypeWithAnnotations Type; internal readonly ArrayBuilder<DeconstructionVariable>? NestedVariables; internal DeconstructionVariable(BoundExpression expression, TypeWithAnnotations type) { Expression = expression; Type = type; NestedVariables = null; } internal DeconstructionVariable(BoundExpression expression, ArrayBuilder<DeconstructionVariable> nestedVariables) { Expression = expression; Type = default; NestedVariables = nestedVariables; } } private ArrayBuilder<DeconstructionVariable> GetDeconstructionAssignmentVariables(BoundTupleExpression tuple) { var arguments = tuple.Arguments; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(arguments.Length); foreach (var argument in arguments) { builder.Add(getDeconstructionAssignmentVariable(argument)); } return builder; DeconstructionVariable getDeconstructionAssignmentVariable(BoundExpression expr) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return new DeconstructionVariable(expr, GetDeconstructionAssignmentVariables((BoundTupleExpression)expr)); default: VisitLValue(expr); return new DeconstructionVariable(expr, LvalueResultType); } } } /// <summary> /// Return the sub-expressions for the righthand side of a deconstruction /// assignment. cf. LocalRewriter.GetRightParts. /// </summary> private ImmutableArray<BoundExpression> GetDeconstructionRightParts(BoundExpression expr, TypeWithState? rightResultOpt) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return ((BoundTupleExpression)expr).Arguments; case BoundKind.Conversion: { var conv = (BoundConversion)expr; switch (conv.ConversionKind) { case ConversionKind.Identity: case ConversionKind.ImplicitTupleLiteral: return GetDeconstructionRightParts(conv.Operand, null); } } break; } if (rightResultOpt is { } rightResult) { expr = CreatePlaceholderIfNecessary(expr, rightResult.ToTypeWithAnnotations(compilation)); } if (expr.Type is NamedTypeSymbol { IsTupleType: true } tupleType) { // https://github.com/dotnet/roslyn/issues/33011: Should include conversion.UnderlyingConversions[i]. // For instance, Boxing conversions (see Deconstruction_ImplicitBoxingConversion_02) and // ImplicitNullable conversions (see Deconstruction_ImplicitNullableConversion_02). var fields = tupleType.TupleElements; return fields.SelectAsArray((f, e) => (BoundExpression)new BoundFieldAccess(e.Syntax, e, f, constantValueOpt: null), expr); } throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitIncrementOperator(BoundIncrementOperator node) { Debug.Assert(!IsConditionalState); var operandType = VisitRvalueWithState(node.Operand); var operandLvalue = LvalueResultType; bool setResult = false; if (this.State.Reachable) { // https://github.com/dotnet/roslyn/issues/29961 Update increment method based on operand type. MethodSymbol? incrementOperator = (node.OperatorKind.IsUserDefined() && node.MethodOpt?.ParameterCount == 1) ? node.MethodOpt : null; TypeWithAnnotations targetTypeOfOperandConversion; AssignmentKind assignmentKind = AssignmentKind.Assignment; ParameterSymbol? parameter = null; // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 // https://github.com/dotnet/roslyn/issues/29961 Update conversion method based on operand type. if (node.OperandConversion is BoundConversion { Conversion: var operandConversion } && operandConversion.IsUserDefined && operandConversion.Method?.ParameterCount == 1) { targetTypeOfOperandConversion = operandConversion.Method.ReturnTypeWithAnnotations; } else if (incrementOperator is object) { targetTypeOfOperandConversion = incrementOperator.Parameters[0].TypeWithAnnotations; assignmentKind = AssignmentKind.Argument; parameter = incrementOperator.Parameters[0]; } else { // Either a built-in increment, or an error case. targetTypeOfOperandConversion = default; } TypeWithState resultOfOperandConversionType; if (targetTypeOfOperandConversion.HasType) { // https://github.com/dotnet/roslyn/issues/29961 Should something special be done for targetTypeOfOperandConversion for lifted case? resultOfOperandConversionType = VisitConversion( conversionOpt: null, node.Operand, BoundNode.GetConversion(node.OperandConversion, node.OperandPlaceholder), targetTypeOfOperandConversion, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind, parameter, reportTopLevelWarnings: true, reportRemainingWarnings: true); } else { resultOfOperandConversionType = operandType; } TypeWithState resultOfIncrementType; if (incrementOperator is null) { resultOfIncrementType = resultOfOperandConversionType; } else { resultOfIncrementType = incrementOperator.ReturnTypeWithAnnotations.ToTypeWithState(); } var operandTypeWithAnnotations = operandType.ToTypeWithAnnotations(compilation); resultOfIncrementType = VisitConversion( conversionOpt: null, node, BoundNode.GetConversion(node.ResultConversion, node.ResultPlaceholder), operandTypeWithAnnotations, resultOfIncrementType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // https://github.com/dotnet/roslyn/issues/29961 Check node.Type.IsErrorType() instead? if (!node.HasErrors) { var op = node.OperatorKind.Operator(); TypeWithState resultType = (op == UnaryOperatorKind.PrefixIncrement || op == UnaryOperatorKind.PrefixDecrement) ? resultOfIncrementType : operandType; SetResultType(node, resultType); setResult = true; TrackNullableStateForAssignment(node, targetType: operandLvalue, targetSlot: MakeSlot(node.Operand), valueType: resultOfIncrementType); } } if (!setResult) { SetNotNullResult(node); } return null; } public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { var left = node.Left; var right = node.Right; Visit(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = declaredType; TypeWithState leftResultType = ResultType; Debug.Assert(!IsConditionalState); TypeWithState leftOnRightType = GetAdjustedResult(leftResultType, MakeSlot(node.Left)); // https://github.com/dotnet/roslyn/issues/29962 Update operator based on inferred argument types. if ((object)node.Operator.LeftType != null) { // https://github.com/dotnet/roslyn/issues/29962 Ignoring top-level nullability of operator left parameter. leftOnRightType = VisitConversion( conversionOpt: null, node.Left, BoundNode.GetConversion(node.LeftConversion, node.LeftPlaceholder), TypeWithAnnotations.Create(node.Operator.LeftType), leftOnRightType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: true); } else { leftOnRightType = default; } TypeWithState resultType; TypeWithState rightType = VisitRvalueWithState(right); if ((object)node.Operator.ReturnType != null) { if (node.Operator.Kind.IsUserDefined() && (object)node.Operator.Method != null && node.Operator.Method.ParameterCount == 2) { MethodSymbol method = node.Operator.Method; VisitArguments(node, ImmutableArray.Create(node.Left, right), method.ParameterRefKinds, method.Parameters, argsToParamsOpt: default, defaultArguments: default, expanded: true, invokedAsExtensionMethod: false, method); } resultType = InferResultNullability(node.Operator.Kind, node.Operator.Method, node.Operator.ReturnType, leftOnRightType, rightType); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(node.Left); leftLValueType = ApplyLValueAnnotations(leftLValueType, leftAnnotations); resultType = VisitConversion( conversionOpt: null, node, BoundNode.GetConversion(node.FinalConversion, node.FinalPlaceholder), leftLValueType, resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, leftAnnotations, node.Syntax.Location); } else { resultType = TypeWithState.Create(node.Type, NullableFlowState.NotNull); } AdjustSetValue(left, ref resultType); TrackNullableStateForAssignment(node, leftLValueType, MakeSlot(node.Left), resultType); SetResultType(node, resultType); return null; } public override BoundNode? VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) { var initializer = node.Expression; if (initializer.Kind == BoundKind.AddressOfOperator) { initializer = ((BoundAddressOfOperator)initializer).Operand; } VisitRvalue(initializer); if (node.Expression.Kind == BoundKind.AddressOfOperator) { SetResultType(node.Expression, TypeWithState.Create(node.Expression.Type, ResultType.State)); } SetNotNullResult(node); return null; } public override BoundNode? VisitAddressOfOperator(BoundAddressOfOperator node) { Visit(node.Operand); SetNotNullResult(node); return null; } private void ReportArgumentWarnings(BoundExpression argument, TypeWithState argumentType, ParameterSymbol parameter) { var paramType = parameter.TypeWithAnnotations; ReportNullableAssignmentIfNecessary(argument, paramType, argumentType, useLegacyWarnings: false, AssignmentKind.Argument, parameterOpt: parameter); if (argumentType.Type is { } argType && IsNullabilityMismatch(paramType.Type, argType)) { ReportNullabilityMismatchInArgument(argument.Syntax, argType, parameter, paramType.Type, forOutput: false); } } private void ReportNullabilityMismatchInRefArgument(BoundExpression argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, argument.Syntax, argumentType, parameterType, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter)); } /// <summary> /// Report warning passing argument where nested nullability does not match /// parameter (e.g.: calling `void F(object[] o)` with `F(new[] { maybeNull })`). /// </summary> private void ReportNullabilityMismatchInArgument(SyntaxNode argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType, bool forOutput) { ReportNullabilityMismatchInArgument(argument.GetLocation(), argumentType, parameter, parameterType, forOutput); } private void ReportNullabilityMismatchInArgument(Location argumentLocation, TypeSymbol argumentType, ParameterSymbol? parameterOpt, TypeSymbol parameterType, bool forOutput) { ReportDiagnostic(forOutput ? ErrorCode.WRN_NullabilityMismatchInArgumentForOutput : ErrorCode.WRN_NullabilityMismatchInArgument, argumentLocation, argumentType, parameterOpt?.Type.IsNonNullableValueType() == true && parameterType.IsNullableType() ? parameterOpt.Type : parameterType, // Compensate for operator lifting GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); } private TypeWithAnnotations GetDeclaredLocalResult(LocalSymbol local) { return _variables.TryGetType(local, out TypeWithAnnotations type) ? type : local.TypeWithAnnotations; } private TypeWithAnnotations GetDeclaredParameterResult(ParameterSymbol parameter) { return _variables.TryGetType(parameter, out TypeWithAnnotations type) ? type : parameter.TypeWithAnnotations; } public override BoundNode? VisitBaseReference(BoundBaseReference node) { VisitThisOrBaseReference(node); return null; } public override BoundNode? VisitFieldAccess(BoundFieldAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.FieldSymbol); SplitIfBooleanConstant(node); SetUpdatedSymbol(node, node.FieldSymbol, updatedSymbol); return null; } public override BoundNode? VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; var updatedMember = VisitMemberAccess(node, node.ReceiverOpt, property); if (!IsAnalyzingAttribute) { if (_expressionIsRead) { ApplyMemberPostConditions(node.ReceiverOpt, property.GetMethod); } else { ApplyMemberPostConditions(node.ReceiverOpt, property.SetMethod); } } SetUpdatedSymbol(node, property, updatedMember); return null; } public override BoundNode? VisitIndexerAccess(BoundIndexerAccess node) { var receiverOpt = node.ReceiverOpt; var receiverType = VisitRvalueWithState(receiverOpt).Type; // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); var indexer = node.Indexer; if (receiverType is object) { // Update indexer based on inferred receiver type. indexer = (PropertySymbol)AsMemberOfType(receiverType, indexer); } VisitArguments(node, node.Arguments, node.ArgumentRefKindsOpt, indexer, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded); var resultType = ApplyUnconditionalAnnotations(indexer.TypeWithAnnotations.ToTypeWithState(), GetRValueAnnotations(indexer)); SetResult(node, resultType, indexer.TypeWithAnnotations); SetUpdatedSymbol(node, node.Indexer, indexer); return null; } public override BoundNode? VisitImplicitIndexerAccess(BoundImplicitIndexerAccess node) { VisitRvalue(node.Receiver); var receiverResult = _visitResult; VisitRvalue(node.Argument); AddPlaceholderReplacement(node.ReceiverPlaceholder, node.Receiver, receiverResult); VisitRvalue(node.IndexerOrSliceAccess); RemovePlaceholderReplacement(node.ReceiverPlaceholder); SetResult(node, ResultType, LvalueResultType); return null; } public override BoundNode? VisitImplicitIndexerValuePlaceholder(BoundImplicitIndexerValuePlaceholder node) { // These placeholders don't need to be replaced because we know they are always not-null AssertPlaceholderAllowedWithoutRegistration(node); SetNotNullResult(node); return null; } public override BoundNode? VisitImplicitIndexerReceiverPlaceholder(BoundImplicitIndexerReceiverPlaceholder node) { VisitPlaceholderWithReplacement(node); return null; } public override BoundNode? VisitEventAccess(BoundEventAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.EventSymbol); SetUpdatedSymbol(node, node.EventSymbol, updatedSymbol); return null; } private Symbol VisitMemberAccess(BoundExpression node, BoundExpression? receiverOpt, Symbol member) { Debug.Assert(!IsConditionalState); var receiverType = (receiverOpt != null) ? VisitRvalueWithState(receiverOpt) : default; SpecialMember? nullableOfTMember = null; if (member.RequiresInstanceReceiver()) { member = AsMemberOfType(receiverType.Type, member); nullableOfTMember = GetNullableOfTMember(member); // https://github.com/dotnet/roslyn/issues/30598: For l-values, mark receiver as not null // after RHS has been visited, and only if the receiver has not changed. bool skipReceiverNullCheck = nullableOfTMember != SpecialMember.System_Nullable_T_get_Value; _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType: !skipReceiverNullCheck); } var type = member.GetTypeOrReturnType(); var memberAnnotations = GetRValueAnnotations(member); var resultType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), memberAnnotations); // We are supposed to track information for the node. Use whatever we managed to // accumulate so far. if (PossiblyNullableType(resultType.Type)) { int slot = MakeMemberSlot(receiverOpt, member); if (this.State.HasValue(slot)) { var state = this.State[slot]; resultType = TypeWithState.Create(resultType.Type, state); } } Debug.Assert(!IsConditionalState); if (nullableOfTMember == SpecialMember.System_Nullable_T_get_HasValue && !(receiverOpt is null)) { int containingSlot = MakeSlot(receiverOpt); if (containingSlot > 0) { Split(); this.StateWhenTrue[containingSlot] = NullableFlowState.NotNull; } } SetResult(node, resultType, type); return member; } private SpecialMember? GetNullableOfTMember(Symbol member) { if (member.Kind == SymbolKind.Property) { var getMethod = ((PropertySymbol)member.OriginalDefinition).GetMethod; if ((object)getMethod != null && getMethod.ContainingType.SpecialType == SpecialType.System_Nullable_T) { if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { return SpecialMember.System_Nullable_T_get_Value; } if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_HasValue)) { return SpecialMember.System_Nullable_T_get_HasValue; } } } return null; } private int GetNullableOfTValueSlot(TypeSymbol containingType, int containingSlot, out Symbol? valueProperty, bool forceSlotEvenIfEmpty = false) { Debug.Assert(containingType.IsNullableType()); Debug.Assert(TypeSymbol.Equals(NominalSlotType(containingSlot), containingType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); var getValue = (MethodSymbol)compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value); valueProperty = getValue?.AsMember((NamedTypeSymbol)containingType)?.AssociatedSymbol; return (valueProperty is null) ? -1 : GetOrCreateSlot(valueProperty, containingSlot, forceSlotEvenIfEmpty: forceSlotEvenIfEmpty); } protected override void VisitForEachExpression(BoundForEachStatement node) { if (node.Expression.Kind != BoundKind.Conversion) { // If we're in this scenario, there was a binding error, and we should suppress any further warnings. Debug.Assert(node.HasErrors); VisitRvalue(node.Expression); return; } var (expr, conversion) = RemoveConversion(node.Expression, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(node.Expression, expr); // There are 7 ways that a foreach can be created: // 1. The collection type is an array type. For this, initial binding will generate an implicit reference conversion to // IEnumerable, and we do not need to do any reinferring of enumerators here. // 2. The collection type is dynamic. For this we do the same as 1. // 3. The collection type implements the GetEnumerator pattern. For this, there is an identity conversion. Because // this identity conversion uses nested types from initial binding, we cannot trust them and must instead use // the type of the expression returned from VisitResult to reinfer the enumerator information. // 4. The collection type implements IEnumerable<T>. Only a few cases can hit this without being caught by number 3, // such as a type with a private implementation of IEnumerable<T>, or a type parameter constrained to that type. // In these cases, there will be an implicit conversion to IEnumerable<T>, but this will use types from // initial binding. For this scenario, we need to look through the list of implemented interfaces on the type and // find the version of IEnumerable<T> that it has after nullable analysis, as type substitution could have changed // nested nullability of type parameters. See ForEach_22 for a concrete example of this. // 5. The collection type implements IEnumerable (non-generic). Because this version isn't generic, we don't need to // do any reinference, and the existing conversion can stand as is. // 6. The target framework's System.String doesn't implement IEnumerable. This is a compat case: System.String normally // does implement IEnumerable, but there are certain target frameworks where this isn't the case. The compiler will // still emit code for foreach in these scenarios. // 7. The collection type implements the GetEnumerator pattern via an extension GetEnumerator. For this, there will be // conversion to the parameter of the extension method. // 8. Some binding error occurred, and some other error has already been reported. Usually this doesn't have any kind // of conversion on top, but if there was an explicit conversion in code then we could get past the initial check // for a BoundConversion node. var resultTypeWithState = VisitRvalueWithState(expr); var resultType = resultTypeWithState.Type; Debug.Assert(resultType is object); SetAnalyzedNullability(expr, _visitResult); TypeWithAnnotations targetTypeWithAnnotations; MethodSymbol? reinferredGetEnumeratorMethod = null; if (node.EnumeratorInfoOpt?.GetEnumeratorInfo is { Method: { IsExtensionMethod: true, Parameters: var parameters } } enumeratorMethodInfo) { // this is case 7 // We do not need to do this same analysis for non-extension methods because they do not have generic parameters that // can be inferred from usage like extension methods can. We don't warn about default arguments at the call site, so // there's nothing that can be learned from the non-extension case. var (method, results, _) = VisitArguments( node, enumeratorMethodInfo.Arguments, refKindsOpt: default, parameters, argsToParamsOpt: enumeratorMethodInfo.ArgsToParamsOpt, defaultArguments: enumeratorMethodInfo.DefaultArguments, expanded: false, invokedAsExtensionMethod: true, enumeratorMethodInfo.Method); targetTypeWithAnnotations = results[0].LValueType; reinferredGetEnumeratorMethod = method; } else if (conversion.IsIdentity || (conversion.Kind == ConversionKind.ExplicitReference && resultType.SpecialType == SpecialType.System_String)) { // This is case 3 or 6. targetTypeWithAnnotations = resultTypeWithState.ToTypeWithAnnotations(compilation); } else if (conversion.IsImplicit) { bool isAsync = node.AwaitOpt != null; if (node.Expression.Type!.SpecialType == SpecialType.System_Collections_IEnumerable) { // If this is a conversion to IEnumerable (non-generic), nothing to do. This is cases 1, 2, and 5. targetTypeWithAnnotations = TypeWithAnnotations.Create(node.Expression.Type); } else if (ForEachLoopBinder.IsIEnumerableT(node.Expression.Type.OriginalDefinition, isAsync, compilation)) { // This is case 4. We need to look for the IEnumerable<T> that this reinferred expression implements, // so that we pick up any nested type substitutions that could have occurred. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; targetTypeWithAnnotations = TypeWithAnnotations.Create(ForEachLoopBinder.GetIEnumerableOfT(resultType, isAsync, compilation, ref discardedUseSiteInfo, out bool foundMultiple)); Debug.Assert(!foundMultiple); Debug.Assert(targetTypeWithAnnotations.HasType); } else { // This is case 8. There was not a successful binding, as a successful binding will _always_ generate one of the // above conversions. Just return, as we want to suppress further errors. return; } } else { // This is also case 8. return; } var convertedResult = VisitConversion( GetConversionIfApplicable(node.Expression, expr), expr, conversion, targetTypeWithAnnotations, resultTypeWithState, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); bool reportedDiagnostic = node.EnumeratorInfoOpt?.GetEnumeratorInfo.Method is { IsExtensionMethod: true } ? false : CheckPossibleNullReceiver(expr); SetAnalyzedNullability(node.Expression, new VisitResult(convertedResult, convertedResult.ToTypeWithAnnotations(compilation))); TypeWithState currentPropertyGetterTypeWithState; if (node.EnumeratorInfoOpt is null) { currentPropertyGetterTypeWithState = default; } else if (resultType is ArrayTypeSymbol arrayType) { // Even though arrays use the IEnumerator pattern, we use the array element type as the foreach target type, so // directly get our source type from there instead of doing method reinference. currentPropertyGetterTypeWithState = arrayType.ElementTypeWithAnnotations.ToTypeWithState(); } else if (resultType.SpecialType == SpecialType.System_String) { // There are frameworks where System.String does not implement IEnumerable, but we still lower it to a for loop // using the indexer over the individual characters anyway. So the type must be not annotated char. currentPropertyGetterTypeWithState = TypeWithAnnotations.Create(node.EnumeratorInfoOpt.ElementType, NullableAnnotation.NotAnnotated).ToTypeWithState(); } else { // Reinfer the return type of the node.Expression.GetEnumerator().Current property, so that if // the collection changed nested generic types we pick up those changes. reinferredGetEnumeratorMethod ??= (MethodSymbol)AsMemberOfType(convertedResult.Type, node.EnumeratorInfoOpt.GetEnumeratorInfo.Method); var enumeratorReturnType = GetReturnTypeWithState(reinferredGetEnumeratorMethod); if (enumeratorReturnType.State != NullableFlowState.NotNull) { if (!reportedDiagnostic && !(node.Expression is BoundConversion { Operand: { IsSuppressed: true } })) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, expr.Syntax.GetLocation()); } } var currentPropertyGetter = (MethodSymbol)AsMemberOfType(enumeratorReturnType.Type, node.EnumeratorInfoOpt.CurrentPropertyGetter); currentPropertyGetterTypeWithState = ApplyUnconditionalAnnotations( currentPropertyGetter.ReturnTypeWithAnnotations.ToTypeWithState(), currentPropertyGetter.ReturnTypeFlowAnalysisAnnotations); // Analyze `await MoveNextAsync()` if (node.AwaitOpt is { AwaitableInstancePlaceholder: BoundAwaitableValuePlaceholder moveNextPlaceholder } awaitMoveNextInfo) { var moveNextAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, node.EnumeratorInfoOpt.MoveNextInfo.Method); var result = new VisitResult(GetReturnTypeWithState(moveNextAsyncMethod), moveNextAsyncMethod.ReturnTypeWithAnnotations); AddPlaceholderReplacement(moveNextPlaceholder, moveNextPlaceholder, result); Visit(awaitMoveNextInfo); RemovePlaceholderReplacement(moveNextPlaceholder); } // Analyze `await DisposeAsync()` if (node.EnumeratorInfoOpt is { NeedsDisposal: true, DisposeAwaitableInfo: BoundAwaitableInfo awaitDisposalInfo }) { var disposalPlaceholder = awaitDisposalInfo.AwaitableInstancePlaceholder; bool addedPlaceholder = false; if (node.EnumeratorInfoOpt.PatternDisposeInfo is { Method: var originalDisposeMethod }) // no statically known Dispose method if doing a runtime check { Debug.Assert(disposalPlaceholder is not null); var disposeAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, originalDisposeMethod); var result = new VisitResult(GetReturnTypeWithState(disposeAsyncMethod), disposeAsyncMethod.ReturnTypeWithAnnotations); AddPlaceholderReplacement(disposalPlaceholder, disposalPlaceholder, result); addedPlaceholder = true; } Visit(awaitDisposalInfo); if (addedPlaceholder) { RemovePlaceholderReplacement(disposalPlaceholder!); } } } SetResultType(expression: null, currentPropertyGetterTypeWithState); } public override void VisitForEachIterationVariables(BoundForEachStatement node) { // ResultType should have been set by VisitForEachExpression, called just before this. var sourceState = node.EnumeratorInfoOpt == null ? default : ResultType; TypeWithAnnotations sourceType = sourceState.ToTypeWithAnnotations(compilation); #pragma warning disable IDE0055 // Fix formatting var variableLocation = node.Syntax switch { ForEachStatementSyntax statement => statement.Identifier.GetLocation(), ForEachVariableStatementSyntax variableStatement => variableStatement.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Syntax) }; #pragma warning restore IDE0055 // Fix formatting if (node.DeconstructionOpt is object) { var assignment = node.DeconstructionOpt.DeconstructionAssignment; // Visit the assignment as a deconstruction with an explicit type VisitDeconstructionAssignmentOperator(assignment, sourceState.HasNullType ? (TypeWithState?)null : sourceState); // https://github.com/dotnet/roslyn/issues/35010: if the iteration variable is a tuple deconstruction, we need to put something in the tree Visit(node.IterationVariableType); } else { Visit(node.IterationVariableType); foreach (var iterationVariable in node.IterationVariables) { var state = NullableFlowState.NotNull; if (!sourceState.HasNullType) { TypeWithAnnotations destinationType = iterationVariable.TypeWithAnnotations; TypeWithState result = sourceState; TypeWithState resultForType = sourceState; if (iterationVariable.IsRef) { // foreach (ref DestinationType variable in collection) if (IsNullabilityMismatch(sourceType, destinationType)) { var foreachSyntax = (ForEachStatementSyntax)node.Syntax; ReportNullabilityMismatchInAssignment(foreachSyntax.Type, sourceType, destinationType); } } else if (iterationVariable is SourceLocalSymbol { IsVar: true }) { // foreach (var variable in collection) destinationType = sourceState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(iterationVariable, destinationType); resultForType = destinationType.ToTypeWithState(); } else { // foreach (DestinationType variable in collection) // and asynchronous variants var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Conversion conversion = BoundNode.GetConversion(node.ElementConversion, node.ElementPlaceholder); if (conversion.Kind == ConversionKind.NoConversion) { conversion = _conversions.ClassifyImplicitConversionFromType(sourceType.Type, destinationType.Type, ref discardedUseSiteInfo); } result = VisitConversion( conversionOpt: null, conversionOperand: node.IterationVariableType, conversion, destinationType, sourceState, checkConversion: true, fromExplicitCast: !conversion.IsImplicit, useLegacyWarnings: true, AssignmentKind.ForEachIterationVariable, reportTopLevelWarnings: true, reportRemainingWarnings: true, diagnosticLocationOpt: variableLocation); } // In non-error cases we'll only run this loop a single time. In error cases we'll set the nullability of the VariableType multiple times, but at least end up with something SetAnalyzedNullability(node.IterationVariableType, new VisitResult(resultForType, destinationType), isLvalue: true); state = result.State; } int slot = GetOrCreateSlot(iterationVariable); if (slot > 0) { this.State[slot] = state; } } } } public override BoundNode? VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { var result = base.VisitFromEndIndexExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitObjectInitializerMember(BoundObjectInitializerMember node) { // Should be handled by VisitObjectCreationExpression. throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { SetNotNullResult(node); return null; } public override BoundNode? VisitBadExpression(BoundBadExpression node) { foreach (var child in node.ChildBoundNodes) { // https://github.com/dotnet/roslyn/issues/35042, we need to implement similar workarounds for object, collection, and dynamic initializers. if (child is BoundLambda lambda) { TakeIncrementalSnapshot(lambda); VisitLambda(lambda, delegateTypeOpt: null); VisitRvalueEpilogue(lambda); } else { VisitRvalue(child as BoundExpression); } } var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return null; } public override BoundNode? VisitTypeExpression(BoundTypeExpression node) { var result = base.VisitTypeExpression(node); if (node.BoundContainingTypeOpt != null) { VisitTypeExpression(node.BoundContainingTypeOpt); } SetNotNullResult(node); return result; } public override BoundNode? VisitTypeOrValueExpression(BoundTypeOrValueExpression node) { // These should not appear after initial binding except in error cases. var result = base.VisitTypeOrValueExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitUnaryOperator(BoundUnaryOperator node) { Debug.Assert(!IsConditionalState); TypeWithState resultType; switch (node.OperatorKind) { case UnaryOperatorKind.BoolLogicalNegation: Visit(node.Operand); if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicTrue: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicLogicalNegation: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); // If the state is split, the result is `bool` at runtime and we invert it here. if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; default: if (node.OperatorKind.IsUserDefined() && node.MethodOpt is MethodSymbol method && method.ParameterCount == 1) { var (operand, conversion) = RemoveConversion(node.Operand, includeExplicitConversions: false); VisitRvalue(operand); var operandResult = ResultType; bool isLifted = node.OperatorKind.IsLifted(); var operandType = GetNullableUnderlyingTypeIfNecessary(isLifted, operandResult); // Update method based on inferred operand type. method = (MethodSymbol)AsMemberOfType(operandType.Type!.StrippedType(), method); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameter = method.Parameters[0]; _ = VisitConversion( node.Operand as BoundConversion, operand, conversion, parameter.TypeWithAnnotations, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter); resultType = GetLiftedReturnTypeIfNecessary(isLifted, method.ReturnTypeWithAnnotations, operandResult.State); SetUpdatedSymbol(node, node.MethodOpt, method); } else { VisitRvalue(node.Operand); resultType = adjustForLifting(ResultType); } break; } SetResultType(node, resultType); return null; TypeWithState adjustForLifting(TypeWithState argumentResult) => TypeWithState.Create(node.Type, node.OperatorKind.IsLifted() ? argumentResult.State : NullableFlowState.NotNull); } public override BoundNode? VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { var result = base.VisitPointerIndirectionOperator(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitPointerElementAccess(BoundPointerElementAccess node) { var result = base.VisitPointerElementAccess(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitRefTypeOperator(BoundRefTypeOperator node) { VisitRvalue(node.Operand); SetNotNullResult(node); return null; } public override BoundNode? VisitMakeRefOperator(BoundMakeRefOperator node) { var result = base.VisitMakeRefOperator(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRefValueOperator(BoundRefValueOperator node) { var result = base.VisitRefValueOperator(node); var type = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetLvalueResultType(node, type); return result; } private TypeWithState InferResultNullability(BoundUserDefinedConditionalLogicalOperator node) { if (node.OperatorKind.IsLifted()) { // https://github.com/dotnet/roslyn/issues/33879 Conversions: Lifted operator // Should this use the updated flow type and state? How should it compute nullability? return TypeWithState.Create(node.Type, NullableFlowState.NotNull); } // Update method based on inferred operand types: see https://github.com/dotnet/roslyn/issues/29605. // Analyze operator result properly (honoring [Maybe|NotNull] and [Maybe|NotNullWhen] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if ((object)node.LogicalOperator != null && node.LogicalOperator.ParameterCount == 2) { return GetReturnTypeWithState(node.LogicalOperator); } else { return default; } } protected override void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression node, BoundExpression right, bool isAnd, bool isBool, ref LocalState leftTrue, ref LocalState leftFalse) { Debug.Assert(!IsConditionalState); TypeWithState leftType = ResultType; // https://github.com/dotnet/roslyn/issues/29605 Update operator methods based on inferred operand types. MethodSymbol? logicalOperator = null; MethodSymbol? trueFalseOperator = null; BoundExpression? left = null; switch (node.Kind) { case BoundKind.BinaryOperator: Debug.Assert(!((BoundBinaryOperator)node).OperatorKind.IsUserDefined()); break; case BoundKind.UserDefinedConditionalLogicalOperator: var binary = (BoundUserDefinedConditionalLogicalOperator)node; if (binary.LogicalOperator != null && binary.LogicalOperator.ParameterCount == 2) { logicalOperator = binary.LogicalOperator; left = binary.Left; trueFalseOperator = isAnd ? binary.FalseOperator : binary.TrueOperator; if ((object)trueFalseOperator != null && trueFalseOperator.ParameterCount != 1) { trueFalseOperator = null; } } break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } Debug.Assert(trueFalseOperator is null || logicalOperator is object); Debug.Assert(logicalOperator is null || left is object); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if (trueFalseOperator is object) { ReportArgumentWarnings(left!, leftType, trueFalseOperator.Parameters[0]); } if (logicalOperator is object) { ReportArgumentWarnings(left!, leftType, logicalOperator.Parameters[0]); } Visit(right); TypeWithState rightType = ResultType; SetResultType(node, InferResultNullabilityOfBinaryLogicalOperator(node, leftType, rightType)); if (logicalOperator is object) { ReportArgumentWarnings(right, rightType, logicalOperator.Parameters[1]); } AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(node, right, isAnd, isBool, ref leftTrue, ref leftFalse); } private TypeWithState InferResultNullabilityOfBinaryLogicalOperator(BoundExpression node, TypeWithState leftType, TypeWithState rightType) { return node switch { BoundBinaryOperator binary => InferResultNullability(binary.OperatorKind, binary.Method, binary.Type, leftType, rightType), BoundUserDefinedConditionalLogicalOperator userDefined => InferResultNullability(userDefined), _ => throw ExceptionUtilities.UnexpectedValue(node) }; } public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) { var result = base.VisitAwaitExpression(node); var awaitableInfo = node.AwaitableInfo; var placeholder = awaitableInfo.AwaitableInstancePlaceholder; Debug.Assert(placeholder is object); AddPlaceholderReplacement(placeholder, node.Expression, _visitResult); Visit(awaitableInfo); RemovePlaceholderReplacement(placeholder); if (node.Type.IsValueType || node.HasErrors || awaitableInfo.GetResult is null) { SetNotNullResult(node); } else { // It is possible for the awaiter type returned from GetAwaiter to not be a named type. e.g. it could be a type parameter. // Proper handling of this is additional work which only benefits a very uncommon scenario, // so we will just use the originally bound GetResult method in this case. var getResult = awaitableInfo.GetResult; var reinferredGetResult = _visitResult.RValueType.Type is NamedTypeSymbol taskAwaiterType ? getResult.OriginalDefinition.AsMember(taskAwaiterType) : getResult; SetResultType(node, reinferredGetResult.ReturnTypeWithAnnotations.ToTypeWithState()); } return result; } public override BoundNode? VisitTypeOfOperator(BoundTypeOfOperator node) { var result = base.VisitTypeOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitMethodInfo(BoundMethodInfo node) { var result = base.VisitMethodInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitFieldInfo(BoundFieldInfo node) { var result = base.VisitFieldInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) { // Can occur in error scenarios and lambda scenarios var result = base.VisitDefaultLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.MaybeDefault)); return result; } public override BoundNode? VisitDefaultExpression(BoundDefaultExpression node) { Debug.Assert(!this.IsConditionalState); var result = base.VisitDefaultExpression(node); TypeSymbol type = node.Type; if (EmptyStructTypeCache.IsTrackableStructType(type)) { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; InheritNullableStateOfTrackableStruct(type, slot, valueSlot: -1, isDefaultValue: true); } } // https://github.com/dotnet/roslyn/issues/33344: this fails to produce an updated tuple type for a default expression // (should produce nullable element types for those elements that are of reference types) SetResultType(node, TypeWithState.ForType(type)); return result; } public override BoundNode? VisitIsOperator(BoundIsOperator node) { Debug.Assert(!this.IsConditionalState); var operand = node.Operand; var typeExpr = node.TargetType; VisitPossibleConditionalAccess(operand, out var conditionalStateWhenNotNull); Unsplit(); LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } Debug.Assert(node.Type.SpecialType == SpecialType.System_Boolean); SetConditionalState(stateWhenNotNull, State); if (typeExpr.Type?.SpecialType == SpecialType.System_Object) { LearnFromNullTest(operand, ref StateWhenFalse); } VisitTypeExpression(typeExpr); SetNotNullResult(node); return null; } public override BoundNode? VisitAsOperator(BoundAsOperator node) { var argumentType = VisitRvalueWithState(node.Operand); NullableFlowState resultState = NullableFlowState.NotNull; var type = node.Type; if (type.CanContainNull()) { switch (BoundNode.GetConversion(node.OperandConversion, node.OperandPlaceholder).Kind) { case ConversionKind.Identity: case ConversionKind.ImplicitReference: case ConversionKind.Boxing: case ConversionKind.ImplicitNullable: resultState = argumentType.State; break; default: resultState = NullableFlowState.MaybeDefault; break; } } VisitTypeExpression(node.TargetType); SetResultType(node, TypeWithState.Create(type, resultState)); return null; } public override BoundNode? VisitSizeOfOperator(BoundSizeOfOperator node) { var result = base.VisitSizeOfOperator(node); VisitTypeExpression(node.SourceType); SetNotNullResult(node); return result; } public override BoundNode? VisitArgList(BoundArgList node) { var result = base.VisitArgList(node); Debug.Assert(node.Type.SpecialType == SpecialType.System_RuntimeArgumentHandle); SetNotNullResult(node); return result; } public override BoundNode? VisitArgListOperator(BoundArgListOperator node) { VisitArgumentsEvaluate(node.Arguments, node.ArgumentRefKindsOpt, parameterAnnotationsOpt: default, defaultArguments: default); Debug.Assert(node.Type is null); SetNotNullResult(node); return null; } public override BoundNode? VisitLiteral(BoundLiteral node) { Debug.Assert(!IsConditionalState); var result = base.VisitLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, node.Type?.CanContainNull() != false && node.ConstantValue?.IsNull == true ? NullableFlowState.MaybeDefault : NullableFlowState.NotNull)); return result; } public override BoundNode? VisitUtf8String(BoundUtf8String node) { Debug.Assert(!IsConditionalState); var result = base.VisitUtf8String(node); SetNotNullResult(node); return result; } public override BoundNode? VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { var result = base.VisitPreviousSubmissionReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitHostObjectMemberReference(BoundHostObjectMemberReference node) { var result = base.VisitHostObjectMemberReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitPseudoVariable(BoundPseudoVariable node) { var result = base.VisitPseudoVariable(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeExpression(BoundRangeExpression node) { var result = base.VisitRangeExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeVariable(BoundRangeVariable node) { VisitWithoutDiagnostics(node.Value); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Need to review this return null; } public override BoundNode? VisitLabel(BoundLabel node) { var result = base.VisitLabel(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitDynamicInvocation(BoundDynamicInvocation node) { var expr = node.Expression; VisitRvalue(expr); // If the expression was a MethodGroup, check nullability of receiver. var receiverOpt = (expr as BoundMethodGroup)?.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } VisitArgumentsEvaluate(node.Arguments, node.ArgumentRefKindsOpt, parameterAnnotationsOpt: default, defaultArguments: default); Debug.Assert(node.Type.IsDynamic()); Debug.Assert(node.Type.IsReferenceType); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { var receiverOpt = node.ReceiverOpt; VisitRvalue(receiverOpt); Debug.Assert(!IsConditionalState); var @event = node.Event; if ([email protected]) { @event = (EventSymbol)AsMemberOfType(ResultType.Type, @event); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); SetUpdatedSymbol(node, node.Event, @event); } VisitRvalue(node.Argument); // https://github.com/dotnet/roslyn/issues/31018: Check for delegate mismatch. if (node.Argument.ConstantValue?.IsNull != true && MakeMemberSlot(receiverOpt, @event) is > 0 and var memberSlot) { this.State[memberSlot] = node.IsAddition ? this.State[memberSlot].Meet(ResultType.State) : NullableFlowState.MaybeNull; } SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29969 Review whether this is the correct result return null; } public override BoundNode? VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { VisitObjectCreationExpressionBase(node); return null; } public override BoundNode? VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitImplicitReceiver(BoundImplicitReceiver node) { var result = base.VisitImplicitReceiver(node); SetNotNullResult(node); return result; } public override BoundNode? VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node) { throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) { VisitObjectCreationExpressionBase(node); return null; } public override BoundNode? VisitNewT(BoundNewT node) { VisitObjectCreationExpressionBase(node); return null; } public override BoundNode? VisitArrayInitialization(BoundArrayInitialization node) { var result = base.VisitArrayInitialization(node); SetNotNullResult(node); return result; } private void SetUnknownResultNullability(BoundExpression expression) { SetResultType(expression, TypeWithState.Create(expression.Type, default)); } public override BoundNode? VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); VisitArgumentsEvaluate(node.Arguments, node.ArgumentRefKindsOpt, parameterAnnotationsOpt: default, defaultArguments: default); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, bool checkNullableValueType = false) { return CheckPossibleNullReceiver(receiverOpt, ResultType, checkNullableValueType); } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, TypeWithState resultType, bool checkNullableValueType) { Debug.Assert(!this.IsConditionalState); bool reportedDiagnostic = false; if (receiverOpt != null && this.State.Reachable) { var resultTypeSymbol = resultType.Type; if (resultTypeSymbol is null) { return false; } #if DEBUG Debug.Assert(receiverOpt.Type is null || AreCloseEnough(receiverOpt.Type, resultTypeSymbol)); #endif if (!ReportPossibleNullReceiverIfNeeded(resultTypeSymbol, resultType.State, checkNullableValueType, receiverOpt.Syntax, out reportedDiagnostic)) { return reportedDiagnostic; } LearnFromNonNullTest(receiverOpt, ref this.State); } return reportedDiagnostic; } // Returns false if the type wasn't interesting private bool ReportPossibleNullReceiverIfNeeded(TypeSymbol type, NullableFlowState state, bool checkNullableValueType, SyntaxNode syntax, out bool reportedDiagnostic) { reportedDiagnostic = false; if (state.MayBeNull()) { bool isValueType = type.IsValueType; if (isValueType && (!checkNullableValueType || !type.IsNullableTypeOrTypeParameter() || type.GetNullableUnderlyingType().IsErrorType())) { return false; } ReportDiagnostic(isValueType ? ErrorCode.WRN_NullableValueTypeMayBeNull : ErrorCode.WRN_NullReferenceReceiver, syntax); reportedDiagnostic = true; } return true; } private void CheckExtensionMethodThisNullability(BoundExpression expr, Conversion conversion, ParameterSymbol parameter, TypeWithState result) { VisitArgumentConversionAndInboundAssignmentsAndPreConditions( conversionOpt: null, expr, conversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(result, result.ToTypeWithAnnotations(compilation)), stateForLambda: default), conversionResultsBuilder: null, extensionMethodThisArgument: true); } private static bool IsNullabilityMismatch(TypeWithAnnotations type1, TypeWithAnnotations type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } private static bool IsNullabilityMismatch(TypeSymbol type1, TypeSymbol type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } public override BoundNode? VisitQueryClause(BoundQueryClause node) { var result = base.VisitQueryClause(node); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Implement nullability analysis in LINQ queries return result; } public override BoundNode? VisitNameOfOperator(BoundNameOfOperator node) { var result = base.VisitNameOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNamespaceExpression(BoundNamespaceExpression node) { var result = base.VisitNamespaceExpression(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) { // This is only involved with unbound lambdas or when visiting the source of a converted tuple literal var result = base.VisitUnconvertedInterpolatedString(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitStringInsert(BoundStringInsert node) { var result = base.VisitStringInsert(node); SetUnknownResultNullability(node); return result; } protected override void VisitInterpolatedStringHandlerConstructor(BoundExpression? constructor) { // We skip visiting the constructor at this stage. We will visit it manually when VisitConversion is // called on the interpolated string handler } public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { // These placeholders don't yet follow proper placeholder discipline AssertPlaceholderAllowedWithoutRegistration(node); SetNotNullResult(node); return null; } public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { VisitPlaceholderWithReplacement(node); return null; } public override BoundNode? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { Debug.Assert(node.Type is null || node.Type.IsErrorType() || node.Type.IsRefLikeType); return VisitStackAllocArrayCreationBase(node); } public override BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { return VisitStackAllocArrayCreationBase(node); } private BoundNode? VisitStackAllocArrayCreationBase(BoundStackAllocArrayCreationBase node) { VisitRvalue(node.Count); var initialization = node.InitializerOpt; if (initialization is null) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return null; } Debug.Assert(node.Type is not null); var type = VisitArrayInitialization(node.Type, initialization, node.HasErrors); SetResultType(node, TypeWithState.Create(type, NullableFlowState.NotNull)); return null; } public override BoundNode? VisitDiscardExpression(BoundDiscardExpression node) { var result = TypeWithAnnotations.Create(node.Type); var rValueType = TypeWithState.ForType(node.Type); SetResult(node, rValueType, result); return null; } public override BoundNode? VisitThrowExpression(BoundThrowExpression node) { VisitThrow(node.Expression); SetResultType(node, default); return null; } public override BoundNode? VisitThrowStatement(BoundThrowStatement node) { VisitThrow(node.ExpressionOpt); return null; } private void VisitThrow(BoundExpression? expr) { if (expr != null) { var result = VisitRvalueWithState(expr); // Cases: // null // null! // Other (typed) expression, including suppressed ones if (result.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_ThrowPossibleNull, expr.Syntax); } } SetUnreachable(); } public override BoundNode? VisitYieldReturnStatement(BoundYieldReturnStatement node) { BoundExpression expr = node.Expression; if (expr == null) { return null; } var method = (MethodSymbol)CurrentSymbol; TypeWithAnnotations elementType = InMethodBinder.GetIteratorElementTypeFromReturnType(compilation, RefKind.None, method.ReturnType, errorLocation: null, diagnostics: null); _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); Unsplit(); return null; } protected override void VisitCatchBlock(BoundCatchBlock node, ref LocalState finallyState) { TakeIncrementalSnapshot(node); if (node.Locals.Length > 0) { LocalSymbol local = node.Locals[0]; if (local.DeclarationKind == LocalDeclarationKind.CatchVariable) { int slot = GetOrCreateSlot(local); if (slot > 0) this.State[slot] = NullableFlowState.NotNull; } } if (node.ExceptionSourceOpt != null) { VisitWithoutDiagnostics(node.ExceptionSourceOpt); } base.VisitCatchBlock(node, ref finallyState); } public override BoundNode? VisitLockStatement(BoundLockStatement node) { VisitRvalue(node.Argument); _ = CheckPossibleNullReceiver(node.Argument); VisitStatement(node.Body); return null; } public override BoundNode? VisitAttribute(BoundAttribute node) { VisitArguments(node, node.ConstructorArguments, ImmutableArray<RefKind>.Empty, node.Constructor, argsToParamsOpt: node.ConstructorArgumentsToParamsOpt, defaultArguments: default, expanded: node.ConstructorExpanded, invokedAsExtensionMethod: false); foreach (var assignment in node.NamedArguments) { Visit(assignment); } SetNotNullResult(node); return null; } public override BoundNode? VisitExpressionWithNullability(BoundExpressionWithNullability node) { var typeWithAnnotations = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetResult(node.Expression, typeWithAnnotations.ToTypeWithState(), typeWithAnnotations); return null; } public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { // These placeholders don't yet follow proper placeholder discipline AssertPlaceholderAllowedWithoutRegistration(node); SetNotNullResult(node); return null; } public override BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { // These placeholders don't yet follow proper placeholder discipline AssertPlaceholderAllowedWithoutRegistration(node); SetNotNullResult(node); return null; } public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { // These placeholders don't always follow proper placeholder discipline yet AssertPlaceholderAllowedWithoutRegistration(node); VisitPlaceholderWithReplacement(node); return null; } private void VisitPlaceholderWithReplacement(BoundValuePlaceholderBase node) { if (_resultForPlaceholdersOpt != null && _resultForPlaceholdersOpt.TryGetValue(node, out var value)) { var result = value.Result; SetResult(node, result.RValueType, result.LValueType); } else { AssertPlaceholderAllowedWithoutRegistration(node); SetNotNullResult(node); } } public override BoundNode? VisitAwaitableInfo(BoundAwaitableInfo node) { Visit(node.AwaitableInstancePlaceholder); Visit(node.GetAwaiter); return null; } public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) { _ = Visit(node.InvokedExpression); Debug.Assert(ResultType is TypeWithState { Type: FunctionPointerTypeSymbol { }, State: NullableFlowState.NotNull }); _ = VisitArguments( node, node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature, argsToParamsOpt: default, defaultArguments: default, expanded: false, invokedAsExtensionMethod: false); var returnTypeWithAnnotations = node.FunctionPointer.Signature.ReturnTypeWithAnnotations; SetResult(node, returnTypeWithAnnotations.ToTypeWithState(), returnTypeWithAnnotations); return null; } protected override string Dump(LocalState state) { return state.Dump(_variables); } protected override bool Meet(ref LocalState self, ref LocalState other) { if (!self.Reachable) return false; if (!other.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Meet(in other); } protected override bool Join(ref LocalState self, ref LocalState other) { if (!other.Reachable) return false; if (!self.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Join(in other); } private void Join(ref PossiblyConditionalState other) { var otherIsConditional = other.IsConditionalState; if (otherIsConditional) { Split(); } if (IsConditionalState) { Join(ref StateWhenTrue, ref otherIsConditional ? ref other.StateWhenTrue : ref other.State); Join(ref StateWhenFalse, ref otherIsConditional ? ref other.StateWhenFalse : ref other.State); } else { Debug.Assert(!otherIsConditional); Join(ref State, ref other.State); } } private LocalState CloneAndUnsplit(ref PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { return conditionalState.State.Clone(); } var state = conditionalState.StateWhenTrue.Clone(); Join(ref state, ref conditionalState.StateWhenFalse); return state; } private void SetPossiblyConditionalState(in PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { SetState(conditionalState.State); } else { SetConditionalState(conditionalState.StateWhenTrue, conditionalState.StateWhenFalse); } } internal sealed class LocalStateSnapshot { internal readonly int Id; internal readonly LocalStateSnapshot? Container; internal readonly BitVector State; internal LocalStateSnapshot(int id, LocalStateSnapshot? container, BitVector state) { Id = id; Container = container; State = state; } } /// <summary> /// A bit array containing the nullability of variables associated with a method scope. If the method is a /// nested function (a lambda or a local function), there is a reference to the corresponding instance for /// the containing method scope. The instances in the chain are associated with a corresponding /// <see cref="Variables"/> chain, and the <see cref="Id"/> field in this type matches <see cref="Variables.Id"/>. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct LocalState : ILocalDataFlowState { private sealed class Boxed { internal LocalState Value; internal Boxed(LocalState value) { Value = value; } } internal readonly int Id; private readonly Boxed? _container; // The representation of a state is a bit vector with two bits per slot: // (false, false) => NotNull, (false, true) => MaybeNull, (true, true) => MaybeDefault. // Slot 0 is used to represent whether the state is reachable (true) or not. private BitVector _state; private LocalState(int id, Boxed? container, BitVector state) { Id = id; _container = container; _state = state; } internal static LocalState Create(LocalStateSnapshot snapshot) { var container = snapshot.Container is null ? null : new Boxed(Create(snapshot.Container)); return new LocalState(snapshot.Id, container, snapshot.State.Clone()); } internal LocalStateSnapshot CreateSnapshot() { return new LocalStateSnapshot(Id, _container?.Value.CreateSnapshot(), _state.Clone()); } public bool Reachable => _state[0]; public bool NormalizeToBottom => false; public static LocalState ReachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: true); } public static LocalState UnreachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: false); } private static LocalState CreateReachableOrUnreachableState(Variables variables, bool reachable) { var container = variables.Container is null ? null : new Boxed(CreateReachableOrUnreachableState(variables.Container, reachable)); int capacity = reachable ? variables.NextAvailableIndex : 1; return new LocalState(variables.Id, container, CreateBitVector(capacity, reachable)); } public LocalState CreateNestedMethodState(Variables variables) { Debug.Assert(Id == variables.Container!.Id); return new LocalState(variables.Id, container: new Boxed(this), CreateBitVector(capacity: variables.NextAvailableIndex, reachable: true)); } private static BitVector CreateBitVector(int capacity, bool reachable) { if (capacity < 1) capacity = 1; BitVector state = BitVector.Create(capacity * 2); state[0] = reachable; return state; } private int Capacity => _state.Capacity / 2; private void EnsureCapacity(int capacity) { _state.EnsureCapacity(capacity * 2); } public bool HasVariable(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasVariable(id, index); } private bool HasVariable(int id, int index) { if (Id > id) { return _container!.Value.HasValue(id, index); } else { return Id == id; } } public bool HasValue(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasValue(id, index); } private bool HasValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.HasValue(id, index); } else { return index < Capacity; } } public void Normalize(NullableWalker walker, Variables variables) { if (Id != variables.Id) { Debug.Assert(Id < variables.Id); Normalize(walker, variables.Container!); } else { _container?.Value.Normalize(walker, variables.Container!); int start = Capacity; EnsureCapacity(variables.NextAvailableIndex); Populate(walker, start); } } public void PopulateAll(NullableWalker walker) { _container?.Value.PopulateAll(walker); Populate(walker, start: 1); } private void Populate(NullableWalker walker, int start) { int capacity = Capacity; for (int index = start; index < capacity; index++) { int slot = Variables.ConstructSlot(Id, index); SetValue(Id, index, walker.GetDefaultState(ref this, slot)); } } public NullableFlowState this[int slot] { get { (int id, int index) = Variables.DeconstructSlot(slot); return GetValue(id, index); } set { (int id, int index) = Variables.DeconstructSlot(slot); SetValue(id, index, value); } } private NullableFlowState GetValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.GetValue(id, index); } else { if (index < Capacity && this.Reachable) { index *= 2; var result = (_state[index + 1], _state[index]) switch { (false, false) => NullableFlowState.NotNull, (false, true) => NullableFlowState.MaybeNull, (true, false) => throw ExceptionUtilities.UnexpectedValue(index), (true, true) => NullableFlowState.MaybeDefault }; return result; } return NullableFlowState.NotNull; } } private void SetValue(int id, int index, NullableFlowState value) { if (Id != id) { Debug.Assert(Id > id); _container!.Value.SetValue(id, index, value); } else { // No states should be modified in unreachable code, as there is only one unreachable state. if (!this.Reachable) return; index *= 2; _state[index] = (value != NullableFlowState.NotNull); _state[index + 1] = (value == NullableFlowState.MaybeDefault); } } internal void ForEach<TArg>(Action<int, TArg> action, TArg arg) { _container?.Value.ForEach(action, arg); for (int index = 1; index < Capacity; index++) { action(Variables.ConstructSlot(Id, index), arg); } } internal LocalState GetStateForVariables(int id) { var state = this; while (state.Id != id) { state = state._container!.Value; } return state; } /// <summary> /// Produce a duplicate of this flow analysis state. /// </summary> /// <returns></returns> public LocalState Clone() { var container = _container is null ? null : new Boxed(_container.Value.Clone()); return new LocalState(Id, container, _state.Clone()); } public bool Join(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Join(in other._container!.Value)) { result = true; } if (_state.UnionWith(in other._state)) { result = true; } return result; } public bool Meet(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Meet(in other._container!.Value)) { result = true; } if (_state.IntersectWith(in other._state)) { result = true; } return result; } internal string GetDebuggerDisplay() { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(" "); int n = Math.Min(Capacity, 8); for (int i = n - 1; i >= 0; i--) builder.Append(_state[i * 2] ? '?' : '!'); return pooledBuilder.ToStringAndFree(); } internal string Dump(Variables variables) { if (!this.Reachable) return "unreachable"; if (Id != variables.Id) return "invalid"; var builder = PooledStringBuilder.GetInstance(); Dump(builder, variables); return builder.ToStringAndFree(); } private void Dump(StringBuilder builder, Variables variables) { _container?.Value.Dump(builder, variables.Container!); for (int index = 1; index < Capacity; index++) { if (getName(Variables.ConstructSlot(Id, index)) is string name) { builder.Append(name); var annotation = GetValue(Id, index) switch { NullableFlowState.MaybeNull => "?", NullableFlowState.MaybeDefault => "??", _ => "!" }; builder.Append(annotation); } } string? getName(int slot) { VariableIdentifier id = variables[slot]; var name = id.Symbol.Name; int containingSlot = id.ContainingSlot; return containingSlot > 0 ? getName(containingSlot) + "." + name : name; } } } internal sealed class LocalFunctionState : AbstractLocalFunctionState { /// <summary> /// Defines the starting state used in the local function body to /// produce diagnostics and determine types. /// </summary> public LocalState StartingState; public LocalFunctionState(LocalState unreachableState) : base(unreachableState.Clone(), unreachableState.Clone()) { StartingState = unreachableState; } } protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol) { var variables = (symbol.ContainingSymbol is MethodSymbol containingMethod ? _variables.GetVariablesForMethodScope(containingMethod) : null) ?? _variables.GetRootScope(); return new LocalFunctionState(LocalState.UnreachableState(variables)); } private sealed class NullabilityInfoTypeComparer : IEqualityComparer<(NullabilityInfo info, TypeSymbol? type)> { public static readonly NullabilityInfoTypeComparer Instance = new NullabilityInfoTypeComparer(); public bool Equals((NullabilityInfo info, TypeSymbol? type) x, (NullabilityInfo info, TypeSymbol? type) y) { return x.info.Equals(y.info) && Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(x.type, y.type); } public int GetHashCode((NullabilityInfo info, TypeSymbol? type) obj) { return obj.GetHashCode(); } } private sealed class ExpressionAndSymbolEqualityComparer : IEqualityComparer<(BoundNode? expr, Symbol symbol)> { internal static readonly ExpressionAndSymbolEqualityComparer Instance = new ExpressionAndSymbolEqualityComparer(); private ExpressionAndSymbolEqualityComparer() { } public bool Equals((BoundNode? expr, Symbol symbol) x, (BoundNode? expr, Symbol symbol) y) { RoslynDebug.Assert(x.symbol is object); RoslynDebug.Assert(y.symbol is object); // We specifically use reference equality for the symbols here because the BoundNode should be immutable. // We should be storing and retrieving the exact same instance of the symbol, not just an "equivalent" // symbol. return x.expr == y.expr && (object)x.symbol == y.symbol; } public int GetHashCode((BoundNode? expr, Symbol symbol) obj) { RoslynDebug.Assert(obj.symbol is object); return Hash.Combine(obj.expr, obj.symbol.GetHashCode()); } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Test/Semantic/Semantics/InteractiveSemanticModelTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class SemanticModelTests : CSharpTestBase { [Fact] public void NamespaceBindingInInteractiveCode() { var compilation = CreateCompilation(@" using Z = Goo.Bar.Script.C; class C { } namespace Goo.Bar { class B : Z { } } ", parseOptions: TestOptions.Script, options: TestOptions.ReleaseExe.WithScriptClassName("Goo.Bar.Script") ); var tree = compilation.SyntaxTrees[0]; var root = tree.GetCompilationUnitRoot(); var classB = (root.Members[1] as NamespaceDeclarationSyntax).Members[0] as TypeDeclarationSyntax; var model = compilation.GetSemanticModel(tree); var symbol = model.GetDeclaredSymbol(classB); var baseType = symbol?.BaseType; Assert.NotNull(baseType); Assert.Equal(TypeKind.Error, baseType.TypeKind); Assert.Equal(LookupResultKind.Inaccessible, baseType.GetSymbol<ErrorTypeSymbol>().ResultKind); // Script class members are private. } [Fact] public void CompilationChain_OverloadsWithParams() { CompileAndVerifyBindInfo(@" public static string[] str = null; public static void Goo(string[] r, string i) { str = r;} public static void Goo(params string[] r) { str = r;} /*<bind>*/ Goo(""1"", ""2"") /*</bind>*/;", "Goo(params string[])"); } [Fact] public void CompilationChain_NestedTypesClass() { CompileAndVerifyBindInfo(@" class InnerClass { public string innerStr = null; public string Goo() { return innerStr;} } InnerClass iC = new InnerClass(); /*<bind>*/ iC.Goo(); /*</bind>*/", "InnerClass.Goo()"); } [Fact] public void MethodCallBinding() { var testSrc = @" void Goo() {}; /*<bind>*/Goo()/*</bind>*/; "; // Get the bind info for the text identified within the commented <bind> </bind> tags var bindInfo = GetBindInfoForTest(testSrc); Assert.NotNull(bindInfo.Type); Assert.Equal("System.Void", bindInfo.Type.ToTestDisplayString()); } [Fact] public void BindNullLiteral() { var testSrc = @"string s = /*<bind>*/null/*</bind>*/;"; // Get the bind info for the text identified within the commented <bind> </bind> tags var bindInfo = GetBindInfoForTest(testSrc); Assert.Null(bindInfo.Type); } [Fact] public void BindBooleanField() { var testSrc = @" bool result = true ; /*<bind>*/ result /*</bind>*/= false; "; // Get the bind info for the text identified within the commented <bind> </bind> tags var bindInfo = GetBindInfoForTest(testSrc); Assert.NotNull(bindInfo.Type); Assert.Equal("System.Boolean", bindInfo.Type.ToTestDisplayString()); } [Fact] public void BindLocals() { var testSrc = @" const int constantField = 1; int field = constantField; { int local1 = field; int local2 = /*<bind>*/local1/*</bind>*/; } { int local2 = constantField; }"; // Get the bind info for the text identified within the commented <bind> </bind> tags var bindInfo = GetBindInfoForTest(testSrc); Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType); var symbol = bindInfo.Symbol; Assert.Equal("System.Int32 local1", symbol.ToTestDisplayString()); Assert.IsAssignableFrom<SourceLocalSymbol>(symbol.GetSymbol()); } [WorkItem(540513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540513")] [Fact] public void BindVariableInGlobalStatement() { var testSrc = @" int i = 2; ++/*<bind>*/i/*</bind>*/;"; // Get the bind info for the text identified within the commented <bind> </bind> tags var bindInfo = GetBindInfoForTest(testSrc); Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType); var symbol = bindInfo.Symbol; Assert.Equal("System.Int32 Script.i", symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, symbol.Kind); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void BindVarKeyword() { var testSrc = @" /*<bind>*/var/*</bind>*/ rand = new System.Random();"; // Get the bind info for the text identified within the commented <bind> </bind> tags var semanticInfo = GetBindInfoForTest(testSrc); Assert.Equal("System.Random", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Random", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Random", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void BindVarKeyword_MultipleDeclarators() { string testSrc = @" /*<bind>*/var/*</bind>*/ i = new int(), j = new char(); "; // Get the bind info for the text identified within the commented <bind> </bind> tags var semanticInfo = GetBindInfoForTest(testSrc); Assert.Equal("var", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("var", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void BindVarNamedType() { string testSrc = @" public class var { } /*<bind>*/var/*</bind>*/ x = new var(); "; // Get the bind info for the text identified within the commented <bind> </bind> tags var semanticInfo = GetBindInfoForTest(testSrc); Assert.Equal("Script.var", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Script.var", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Script.var", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void BindVarNamedType_Ambiguous() { string testSrc = @" using System; public class var { } public struct var { } /*<bind>*/var/*</bind>*/ x = new var(); "; // Get the bind info for the text identified within the commented <bind> </bind> tags var semanticInfo = GetBindInfoForTest(testSrc); Assert.Equal("Script.var", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("Script.var", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString()).ToArray(); Assert.Equal("Script.var", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("Script.var", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543864")] [Fact] public void BindQueryVariable() { string testSrc = @" using System.Linq; var x = from c in ""goo"" select /*<bind>*/c/*</bind>*/"; // Get the bind info for the text identified within the commented <bind> </bind> tags var semanticInfo = GetBindInfoForTest(testSrc); Assert.Equal("c", semanticInfo.Symbol.Name); Assert.Equal(SymbolKind.RangeVariable, semanticInfo.Symbol.Kind); Assert.Equal(SpecialType.System_Char, semanticInfo.Type.SpecialType); } #region helpers private List<ExpressionSyntax> GetExprSyntaxList(SyntaxTree syntaxTree) { return GetExprSyntaxList(syntaxTree.GetCompilationUnitRoot(), null); } private List<ExpressionSyntax> GetExprSyntaxList(SyntaxNode node, List<ExpressionSyntax> exprSynList) { if (exprSynList == null) exprSynList = new List<ExpressionSyntax>(); if (node is ExpressionSyntax) { exprSynList.Add(node as ExpressionSyntax); } foreach (var child in node.ChildNodesAndTokens()) { if (child.IsNode) exprSynList = GetExprSyntaxList(child.AsNode(), exprSynList); } return exprSynList; } private ExpressionSyntax GetExprSyntaxForBinding(List<ExpressionSyntax> exprSynList) { foreach (var exprSyntax in exprSynList) { string exprFullText = exprSyntax.ToFullString(); exprFullText = exprFullText.Trim(); if (exprFullText.StartsWith("/*<bind>*/", StringComparison.Ordinal)) { if (exprFullText.Contains("/*</bind>*/")) { if (exprFullText.EndsWith("/*</bind>*/", StringComparison.Ordinal)) { return exprSyntax; } else { continue; } } else { return exprSyntax; } } if (exprFullText.EndsWith("/*</bind>*/", StringComparison.Ordinal)) { if (exprFullText.Contains("/*<bind>*/")) { if (exprFullText.StartsWith("/*<bind>*/", StringComparison.Ordinal)) { return exprSyntax; } else { continue; } } else { return exprSyntax; } } } return null; } private void CompileAndVerifyBindInfo(string testSrc, string expected) { // Get the bind info for the text identified within the commented <bind> </bind> tags var bindInfo = GetBindInfoForTest(testSrc); Assert.NotNull(bindInfo.Type); var method = bindInfo.Symbol.ToDisplayString(); Assert.Equal(expected, method); } private CompilationUtils.SemanticInfoSummary GetBindInfoForTest(string testSrc) { var compilation = CreateCompilation(testSrc, parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); return model.GetSemanticInfoSummary(exprSyntaxToBind); } #endregion helpers } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class SemanticModelTests : CSharpTestBase { [Fact] public void NamespaceBindingInInteractiveCode() { var compilation = CreateCompilation(@" using Z = Goo.Bar.Script.C; class C { } namespace Goo.Bar { class B : Z { } } ", parseOptions: TestOptions.Script, options: TestOptions.ReleaseExe.WithScriptClassName("Goo.Bar.Script") ); var tree = compilation.SyntaxTrees[0]; var root = tree.GetCompilationUnitRoot(); var classB = (root.Members[1] as NamespaceDeclarationSyntax).Members[0] as TypeDeclarationSyntax; var model = compilation.GetSemanticModel(tree); var symbol = model.GetDeclaredSymbol(classB); var baseType = symbol?.BaseType; Assert.NotNull(baseType); Assert.Equal(TypeKind.Error, baseType.TypeKind); Assert.Equal(LookupResultKind.Inaccessible, baseType.GetSymbol<ErrorTypeSymbol>().ResultKind); // Script class members are private. } [Fact] public void CompilationChain_OverloadsWithParams() { CompileAndVerifyBindInfo(@" public static string[] str = null; public static void Goo(string[] r, string i) { str = r;} public static void Goo(params string[] r) { str = r;} /*<bind>*/ Goo(""1"", ""2"") /*</bind>*/;", "Goo(params string[])"); } [Fact] public void CompilationChain_NestedTypesClass() { CompileAndVerifyBindInfo(@" class InnerClass { public string innerStr = null; public string Goo() { return innerStr;} } InnerClass iC = new InnerClass(); /*<bind>*/ iC.Goo(); /*</bind>*/", "InnerClass.Goo()"); } [Fact] public void MethodCallBinding() { var testSrc = @" void Goo() {}; /*<bind>*/Goo()/*</bind>*/; "; // Get the bind info for the text identified within the commented <bind> </bind> tags var bindInfo = GetBindInfoForTest(testSrc); Assert.NotNull(bindInfo.Type); Assert.Equal("System.Void", bindInfo.Type.ToTestDisplayString()); } [Fact] public void BindNullLiteral() { var testSrc = @"string s = /*<bind>*/null/*</bind>*/;"; // Get the bind info for the text identified within the commented <bind> </bind> tags var bindInfo = GetBindInfoForTest(testSrc); Assert.Null(bindInfo.Type); } [Fact] public void BindBooleanField() { var testSrc = @" bool result = true ; /*<bind>*/ result /*</bind>*/= false; "; // Get the bind info for the text identified within the commented <bind> </bind> tags var bindInfo = GetBindInfoForTest(testSrc); Assert.NotNull(bindInfo.Type); Assert.Equal("System.Boolean", bindInfo.Type.ToTestDisplayString()); } [Fact] public void BindLocals() { var testSrc = @" const int constantField = 1; int field = constantField; { int local1 = field; int local2 = /*<bind>*/local1/*</bind>*/; } { int local2 = constantField; }"; // Get the bind info for the text identified within the commented <bind> </bind> tags var bindInfo = GetBindInfoForTest(testSrc); Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType); var symbol = bindInfo.Symbol; Assert.Equal("System.Int32 local1", symbol.ToTestDisplayString()); Assert.IsAssignableFrom<SourceLocalSymbol>(symbol.GetSymbol()); } [WorkItem(540513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540513")] [Fact] public void BindVariableInGlobalStatement() { var testSrc = @" int i = 2; ++/*<bind>*/i/*</bind>*/;"; // Get the bind info for the text identified within the commented <bind> </bind> tags var bindInfo = GetBindInfoForTest(testSrc); Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType); var symbol = bindInfo.Symbol; Assert.Equal("System.Int32 Script.i", symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, symbol.Kind); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void BindVarKeyword() { var testSrc = @" /*<bind>*/var/*</bind>*/ rand = new System.Random();"; // Get the bind info for the text identified within the commented <bind> </bind> tags var semanticInfo = GetBindInfoForTest(testSrc); Assert.Equal("System.Random", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Random", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Random", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void BindVarKeyword_MultipleDeclarators() { string testSrc = @" /*<bind>*/var/*</bind>*/ i = new int(), j = new char(); "; // Get the bind info for the text identified within the commented <bind> </bind> tags var semanticInfo = GetBindInfoForTest(testSrc); Assert.Equal("var", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("var", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void BindVarNamedType() { string testSrc = @" public class var { } /*<bind>*/var/*</bind>*/ x = new var(); "; // Get the bind info for the text identified within the commented <bind> </bind> tags var semanticInfo = GetBindInfoForTest(testSrc); Assert.Equal("Script.var", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Script.var", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Script.var", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void BindVarNamedType_Ambiguous() { string testSrc = @" using System; public class var { } public struct var { } /*<bind>*/var/*</bind>*/ x = new var(); "; // Get the bind info for the text identified within the commented <bind> </bind> tags var semanticInfo = GetBindInfoForTest(testSrc); Assert.Equal("Script.var", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("Script.var", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString()).ToArray(); Assert.Equal("Script.var", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("Script.var", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543864")] [Fact] public void BindQueryVariable() { string testSrc = @" using System.Linq; var x = from c in ""goo"" select /*<bind>*/c/*</bind>*/"; // Get the bind info for the text identified within the commented <bind> </bind> tags var semanticInfo = GetBindInfoForTest(testSrc); Assert.Equal("c", semanticInfo.Symbol.Name); Assert.Equal(SymbolKind.RangeVariable, semanticInfo.Symbol.Kind); Assert.Equal(SpecialType.System_Char, semanticInfo.Type.SpecialType); } #region helpers private List<ExpressionSyntax> GetExprSyntaxList(SyntaxTree syntaxTree) { return GetExprSyntaxList(syntaxTree.GetCompilationUnitRoot(), null); } private List<ExpressionSyntax> GetExprSyntaxList(SyntaxNode node, List<ExpressionSyntax> exprSynList) { if (exprSynList == null) exprSynList = new List<ExpressionSyntax>(); if (node is ExpressionSyntax) { exprSynList.Add(node as ExpressionSyntax); } foreach (var child in node.ChildNodesAndTokens()) { if (child.IsNode) exprSynList = GetExprSyntaxList(child.AsNode(), exprSynList); } return exprSynList; } private ExpressionSyntax GetExprSyntaxForBinding(List<ExpressionSyntax> exprSynList) { foreach (var exprSyntax in exprSynList) { string exprFullText = exprSyntax.ToFullString(); exprFullText = exprFullText.Trim(); if (exprFullText.StartsWith("/*<bind>*/", StringComparison.Ordinal)) { if (exprFullText.Contains("/*</bind>*/")) { if (exprFullText.EndsWith("/*</bind>*/", StringComparison.Ordinal)) { return exprSyntax; } else { continue; } } else { return exprSyntax; } } if (exprFullText.EndsWith("/*</bind>*/", StringComparison.Ordinal)) { if (exprFullText.Contains("/*<bind>*/")) { if (exprFullText.StartsWith("/*<bind>*/", StringComparison.Ordinal)) { return exprSyntax; } else { continue; } } else { return exprSyntax; } } } return null; } private void CompileAndVerifyBindInfo(string testSrc, string expected) { // Get the bind info for the text identified within the commented <bind> </bind> tags var bindInfo = GetBindInfoForTest(testSrc); Assert.NotNull(bindInfo.Type); var method = bindInfo.Symbol.ToDisplayString(); Assert.Equal(expected, method); } private CompilationUtils.SemanticInfoSummary GetBindInfoForTest(string testSrc) { var compilation = CreateCompilation(testSrc, parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); return model.GetSemanticInfoSummary(exprSyntaxToBind); } #endregion helpers } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/BoundTree/BoundDagTemp.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { #if DEBUG [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] #endif partial class BoundDagTemp { /// <summary> /// Does this dag temp represent the original input of the pattern-matching operation? /// </summary> public bool IsOriginalInput => this.Source is null; public static BoundDagTemp ForOriginalInput(SyntaxNode syntax, TypeSymbol type) => new BoundDagTemp(syntax, type, source: null, 0); public override bool Equals(object? obj) => obj is BoundDagTemp other && this.Equals(other); public bool Equals(BoundDagTemp other) { return this.Type.Equals(other.Type, TypeCompareKind.AllIgnoreOptions) && object.Equals(this.Source, other.Source) && this.Index == other.Index; } /// <summary> /// Check if this is equivalent to the <paramref name="other"/> node, ignoring the source. /// </summary> public bool IsEquivalentTo(BoundDagTemp other) { return this.Type.Equals(other.Type, TypeCompareKind.AllIgnoreOptions) && this.Index == other.Index; } public override int GetHashCode() { return Hash.Combine(this.Type.GetHashCode(), Hash.Combine(this.Source?.GetHashCode() ?? 0, this.Index)); } #if DEBUG internal new string GetDebuggerDisplay() { var name = Source?.Id switch { -1 => "<uninitialized>", // Note that we never expect to have a non-null source with id 0 // because id 0 is reserved for the original input. // However, we also don't want to assert in a debugger display method. 0 => "<error>", null => "t0", var id => $"t{id}" }; return $"{name}{(Source is BoundDagDeconstructEvaluation ? $".Item{(Index + 1).ToString()}" : "")}"; } #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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { #if DEBUG [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] #endif partial class BoundDagTemp { /// <summary> /// Does this dag temp represent the original input of the pattern-matching operation? /// </summary> public bool IsOriginalInput => this.Source is null; public static BoundDagTemp ForOriginalInput(SyntaxNode syntax, TypeSymbol type) => new BoundDagTemp(syntax, type, source: null, 0); public override bool Equals(object? obj) => obj is BoundDagTemp other && this.Equals(other); public bool Equals(BoundDagTemp other) { return this.Type.Equals(other.Type, TypeCompareKind.AllIgnoreOptions) && object.Equals(this.Source, other.Source) && this.Index == other.Index; } /// <summary> /// Check if this is equivalent to the <paramref name="other"/> node, ignoring the source. /// </summary> public bool IsEquivalentTo(BoundDagTemp other) { return this.Type.Equals(other.Type, TypeCompareKind.AllIgnoreOptions) && this.Index == other.Index; } public override int GetHashCode() { return Hash.Combine(this.Type.GetHashCode(), Hash.Combine(this.Source?.GetHashCode() ?? 0, this.Index)); } #if DEBUG internal new string GetDebuggerDisplay() { var name = Source?.Id switch { -1 => "<uninitialized>", // Note that we never expect to have a non-null source with id 0 // because id 0 is reserved for the original input. // However, we also don't want to assert in a debugger display method. 0 => "<error>", null => "t0", var id => $"t{id}" }; return $"{name}{(Source is BoundDagDeconstructEvaluation ? $".Item{(Index + 1).ToString()}" : "")}"; } #endif } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/Core.Wpf/SignatureHelp/Controller.Session.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal partial class Session : Session<Controller, Model, ISignatureHelpPresenterSession> { public Session(Controller controller, ISignatureHelpPresenterSession presenterSession) : base(controller, new ModelComputation<Model>(controller.ThreadingContext, controller, TaskScheduler.Default), presenterSession) { this.PresenterSession.ItemSelected += OnPresenterSessionItemSelected; } public override void Stop() { this.Computation.ThreadingContext.ThrowIfNotOnUIThread(); this.PresenterSession.ItemSelected -= OnPresenterSessionItemSelected; base.Stop(); } private void OnPresenterSessionItemSelected(object sender, SignatureHelpItemEventArgs e) { this.Computation.ThreadingContext.ThrowIfNotOnUIThread(); Contract.ThrowIfFalse(ReferenceEquals(this.PresenterSession, sender)); SetModelExplicitlySelectedItem(m => e.SignatureHelpItem); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal partial class Session : Session<Controller, Model, ISignatureHelpPresenterSession> { public Session(Controller controller, ISignatureHelpPresenterSession presenterSession) : base(controller, new ModelComputation<Model>(controller.ThreadingContext, controller, TaskScheduler.Default), presenterSession) { this.PresenterSession.ItemSelected += OnPresenterSessionItemSelected; } public override void Stop() { this.Computation.ThreadingContext.ThrowIfNotOnUIThread(); this.PresenterSession.ItemSelected -= OnPresenterSessionItemSelected; base.Stop(); } private void OnPresenterSessionItemSelected(object sender, SignatureHelpItemEventArgs e) { this.Computation.ThreadingContext.ThrowIfNotOnUIThread(); Contract.ThrowIfFalse(ReferenceEquals(this.PresenterSession, sender)); SetModelExplicitlySelectedItem(m => e.SignatureHelpItem); } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/CSharp/Portable/CodeRefactorings/NodeSelectionHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings { internal static class NodeSelectionHelpers { internal static async Task<ImmutableArray<SyntaxNode>> GetSelectedDeclarationsOrVariablesAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; if (span.IsEmpty) { // if the span is empty then we are only selecting one "member" (which could include a field which declared multiple actual members) // Consider: // MemberDeclaration: member that can be declared in type (those are the ones we can pull up) // VariableDeclaratorSyntax: for fields the MemberDeclaration can actually represent multiple declarations, e.g. `int a = 0, b = 1;`. // ..Since the user might want to select & pull up only one of them (e.g. `int a = 0, [|b = 1|];` we also look for closest VariableDeclaratorSyntax. var memberDeclaration = await context.TryGetRelevantNodeAsync<MemberDeclarationSyntax>().ConfigureAwait(false); if (memberDeclaration == null) { // could not find a member, we may be directly on a variable declaration var varDeclarator = await context.TryGetRelevantNodeAsync<VariableDeclaratorSyntax>().ConfigureAwait(false); return varDeclarator == null ? ImmutableArray<SyntaxNode>.Empty : ImmutableArray.Create<SyntaxNode>(varDeclarator); } else { return memberDeclaration switch { FieldDeclarationSyntax fieldDeclaration => fieldDeclaration.Declaration.Variables.AsImmutable<SyntaxNode>(), EventFieldDeclarationSyntax eventFieldDeclaration => eventFieldDeclaration.Declaration.Variables.AsImmutable<SyntaxNode>(), IncompleteMemberSyntax or GlobalStatementSyntax => ImmutableArray<SyntaxNode>.Empty, _ => ImmutableArray.Create<SyntaxNode>(memberDeclaration), }; } } else { // if the span is non-empty, then we get potentially multiple members // Note: even though this method handles the empty span case, we don't use it because it doesn't correctly // pick up on keywords before the declaration, such as "public static int". // We could potentially use it for every case if that behavior changes var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var members = await CSharpSelectedMembers.Instance.GetSelectedMembersAsync(tree, span, allowPartialSelection: true, cancellationToken).ConfigureAwait(false); // if we get a node that would not have an obtainable symbol (such as the ones below) // we return an empty list instead of filtering so we don't get other potentially // malformed syntax nodes. // Consider pub[||] static int Foo; // Which has 2 member nodes (an incomplete and a field), but we'd only expect one return members.Any(m => m is GlobalStatementSyntax or IncompleteMemberSyntax) ? ImmutableArray<SyntaxNode>.Empty : members; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings { internal static class NodeSelectionHelpers { internal static async Task<ImmutableArray<SyntaxNode>> GetSelectedDeclarationsOrVariablesAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; if (span.IsEmpty) { // if the span is empty then we are only selecting one "member" (which could include a field which declared multiple actual members) // Consider: // MemberDeclaration: member that can be declared in type (those are the ones we can pull up) // VariableDeclaratorSyntax: for fields the MemberDeclaration can actually represent multiple declarations, e.g. `int a = 0, b = 1;`. // ..Since the user might want to select & pull up only one of them (e.g. `int a = 0, [|b = 1|];` we also look for closest VariableDeclaratorSyntax. var memberDeclaration = await context.TryGetRelevantNodeAsync<MemberDeclarationSyntax>().ConfigureAwait(false); if (memberDeclaration == null) { // could not find a member, we may be directly on a variable declaration var varDeclarator = await context.TryGetRelevantNodeAsync<VariableDeclaratorSyntax>().ConfigureAwait(false); return varDeclarator == null ? ImmutableArray<SyntaxNode>.Empty : ImmutableArray.Create<SyntaxNode>(varDeclarator); } else { return memberDeclaration switch { FieldDeclarationSyntax fieldDeclaration => fieldDeclaration.Declaration.Variables.AsImmutable<SyntaxNode>(), EventFieldDeclarationSyntax eventFieldDeclaration => eventFieldDeclaration.Declaration.Variables.AsImmutable<SyntaxNode>(), IncompleteMemberSyntax or GlobalStatementSyntax => ImmutableArray<SyntaxNode>.Empty, _ => ImmutableArray.Create<SyntaxNode>(memberDeclaration), }; } } else { // if the span is non-empty, then we get potentially multiple members // Note: even though this method handles the empty span case, we don't use it because it doesn't correctly // pick up on keywords before the declaration, such as "public static int". // We could potentially use it for every case if that behavior changes var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var members = await CSharpSelectedMembers.Instance.GetSelectedMembersAsync(tree, span, allowPartialSelection: true, cancellationToken).ConfigureAwait(false); // if we get a node that would not have an obtainable symbol (such as the ones below) // we return an empty list instead of filtering so we don't get other potentially // malformed syntax nodes. // Consider pub[||] static int Foo; // Which has 2 member nodes (an incomplete and a field), but we'd only expect one return members.Any(m => m is GlobalStatementSyntax or IncompleteMemberSyntax) ? ImmutableArray<SyntaxNode>.Empty : members; } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/Core/Portable/Diagnostics/AnalysisKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics { /// <summary> /// enum for each analysis kind. /// </summary> internal enum AnalysisKind { Syntax, Semantic, NonLocal } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics { /// <summary> /// enum for each analysis kind. /// </summary> internal enum AnalysisKind { Syntax, Semantic, NonLocal } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/ValueTracking/TreeViewItemBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.VisualStudio.LanguageServices.Utilities; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class TreeViewItemBase : ViewModelBase { public ObservableCollection<TreeViewItemBase> ChildItems { get; } = new(); public TreeViewItemBase? Parent { get; set; } public virtual string AutomationName { get; } = string.Empty; private bool _isExpanded = false; public virtual bool IsNodeExpanded { get => _isExpanded; set => SetProperty(ref _isExpanded, value); } private bool _isSelected = false; public bool IsNodeSelected { get => _isSelected; set => SetProperty(ref _isSelected, value); } private bool _isLoading; public bool IsLoading { get => _isLoading; set => SetProperty(ref _isLoading, value); } public TreeViewItemBase() { ChildItems.CollectionChanged += ChildItems_CollectionChanged; } /// <summary> /// Returns the next logical item in the tree that could be seen (Parent is expanded) /// </summary> public TreeViewItemBase GetNextInTree() { if (IsNodeExpanded && ChildItems.Any()) { return ChildItems.First(); } var sibling = GetSibling(next: true); if (sibling is not null) { return sibling; } return Parent?.GetSibling(next: true) ?? this; } /// <summary> /// Returns the previous logical item in the tree that could be seen (Parent is expanded) /// </summary> public TreeViewItemBase GetPreviousInTree() { var sibling = GetSibling(next: false); if (sibling is not null) { return sibling.GetLastVisibleDescendentOrSelf(); } return Parent ?? this; } private TreeViewItemBase GetLastVisibleDescendentOrSelf() { if (!IsNodeExpanded || ChildItems.Count == 0) { return this; } var lastChild = ChildItems.Last(); return lastChild.GetLastVisibleDescendentOrSelf(); } private TreeViewItemBase? GetSibling(bool next = true) { if (Parent is null) { return null; } var thisIndex = Parent.ChildItems.IndexOf(this); var siblingIndex = next ? thisIndex + 1 : thisIndex - 1; if (siblingIndex < 0 || siblingIndex >= Parent.ChildItems.Count) { return null; } return Parent.ChildItems[siblingIndex]; } private void ChildItems_CollectionChanged(object _, NotifyCollectionChangedEventArgs args) { if (args.Action is not NotifyCollectionChangedAction.Add and not NotifyCollectionChangedAction.Remove) { return; } SetParents(args.OldItems, null); SetParents(args.NewItems, this); static void SetParents(IList? items, TreeViewItemBase? parent) { if (items is null) { return; } foreach (var item in items.Cast<TreeViewItemBase>()) { item.Parent = parent; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.VisualStudio.LanguageServices.Utilities; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class TreeViewItemBase : ViewModelBase { public ObservableCollection<TreeViewItemBase> ChildItems { get; } = new(); public TreeViewItemBase? Parent { get; set; } public virtual string AutomationName { get; } = string.Empty; private bool _isExpanded = false; public virtual bool IsNodeExpanded { get => _isExpanded; set => SetProperty(ref _isExpanded, value); } private bool _isSelected = false; public bool IsNodeSelected { get => _isSelected; set => SetProperty(ref _isSelected, value); } private bool _isLoading; public bool IsLoading { get => _isLoading; set => SetProperty(ref _isLoading, value); } public TreeViewItemBase() { ChildItems.CollectionChanged += ChildItems_CollectionChanged; } /// <summary> /// Returns the next logical item in the tree that could be seen (Parent is expanded) /// </summary> public TreeViewItemBase GetNextInTree() { if (IsNodeExpanded && ChildItems.Any()) { return ChildItems.First(); } var sibling = GetSibling(next: true); if (sibling is not null) { return sibling; } return Parent?.GetSibling(next: true) ?? this; } /// <summary> /// Returns the previous logical item in the tree that could be seen (Parent is expanded) /// </summary> public TreeViewItemBase GetPreviousInTree() { var sibling = GetSibling(next: false); if (sibling is not null) { return sibling.GetLastVisibleDescendentOrSelf(); } return Parent ?? this; } private TreeViewItemBase GetLastVisibleDescendentOrSelf() { if (!IsNodeExpanded || ChildItems.Count == 0) { return this; } var lastChild = ChildItems.Last(); return lastChild.GetLastVisibleDescendentOrSelf(); } private TreeViewItemBase? GetSibling(bool next = true) { if (Parent is null) { return null; } var thisIndex = Parent.ChildItems.IndexOf(this); var siblingIndex = next ? thisIndex + 1 : thisIndex - 1; if (siblingIndex < 0 || siblingIndex >= Parent.ChildItems.Count) { return null; } return Parent.ChildItems[siblingIndex]; } private void ChildItems_CollectionChanged(object _, NotifyCollectionChangedEventArgs args) { if (args.Action is not NotifyCollectionChangedAction.Add and not NotifyCollectionChangedAction.Remove) { return; } SetParents(args.OldItems, null); SetParents(args.NewItems, this); static void SetParents(IList? items, TreeViewItemBase? parent) { if (items is null) { return; } foreach (var item in items.Cast<TreeViewItemBase>()) { item.Parent = parent; } } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SemanticFacts/CSharpSemanticFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class CSharpSemanticFacts : ISemanticFacts { internal static readonly CSharpSemanticFacts Instance = new(); private CSharpSemanticFacts() { } public ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; public bool SupportsImplicitInterfaceImplementation => true; public bool ExposesAnonymousFunctionParameterNames => false; public bool IsWrittenTo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => (node as ExpressionSyntax).IsWrittenTo(semanticModel, cancellationToken); public bool IsOnlyWrittenTo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => (node as ExpressionSyntax).IsOnlyWrittenTo(); public bool IsInOutContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => (node as ExpressionSyntax).IsInOutContext(); public bool IsInRefContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => (node as ExpressionSyntax).IsInRefContext(); public bool IsInInContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => (node as ExpressionSyntax).IsInInContext(); public bool CanReplaceWithRValue(SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken) => (expression as ExpressionSyntax).CanReplaceWithRValue(semanticModel, cancellationToken); public ISymbol GetDeclaredSymbol(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { var location = token.GetLocation(); foreach (var ancestor in token.GetAncestors<SyntaxNode>()) { var symbol = semanticModel.GetDeclaredSymbol(ancestor, cancellationToken); if (symbol != null) { if (symbol is IMethodSymbol { MethodKind: MethodKind.Conversion }) { // The token may be part of a larger name (for example, `int` in `public static operator int[](Goo g);`. // So check if the symbol's location encompasses the span of the token we're asking about. if (symbol.Locations.Any(static (loc, location) => loc.SourceTree == location.SourceTree && loc.SourceSpan.Contains(location.SourceSpan), location)) return symbol; } else { // For any other symbols, we only care if the name directly matches the span of the token if (symbol.Locations.Contains(location)) return symbol; } // We found some symbol, but it defined something else. We're not going to have a higher node defining _another_ symbol with this token, so we can stop now. return null; } // If we hit an executable statement syntax and didn't find anything yet, we can just stop now -- anything higher would be a member declaration which won't be defined by something inside a statement. if (CSharpSyntaxFacts.Instance.IsExecutableStatement(ancestor)) { return null; } } return null; } public bool LastEnumValueHasInitializer(INamedTypeSymbol namedTypeSymbol) { var enumDecl = namedTypeSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).OfType<EnumDeclarationSyntax>().FirstOrDefault(); if (enumDecl != null) { var lastMember = enumDecl.Members.LastOrDefault(); if (lastMember != null) { return lastMember.EqualsValue != null; } } return false; } public bool SupportsParameterizedProperties => false; public bool TryGetSpeculativeSemanticModel(SemanticModel oldSemanticModel, SyntaxNode oldNode, SyntaxNode newNode, out SemanticModel speculativeModel) { Debug.Assert(oldNode.Kind() == newNode.Kind()); var model = oldSemanticModel; if (oldNode is not BaseMethodDeclarationSyntax oldMethod || newNode is not BaseMethodDeclarationSyntax newMethod || oldMethod.Body == null) { speculativeModel = null; return false; } var success = model.TryGetSpeculativeSemanticModelForMethodBody(oldMethod.Body.OpenBraceToken.Span.End, newMethod, out var csharpModel); speculativeModel = csharpModel; return success; } public ImmutableHashSet<string> GetAliasNameSet(SemanticModel model, CancellationToken cancellationToken) { var original = model.GetOriginalSemanticModel(); if (!original.SyntaxTree.HasCompilationUnitRoot) { return ImmutableHashSet.Create<string>(); } var root = original.SyntaxTree.GetCompilationUnitRoot(cancellationToken); var builder = ImmutableHashSet.CreateBuilder<string>(StringComparer.Ordinal); AppendAliasNames(root.Usings, builder); AppendAliasNames(root.Members.OfType<BaseNamespaceDeclarationSyntax>(), builder, cancellationToken); return builder.ToImmutable(); } private static void AppendAliasNames(SyntaxList<UsingDirectiveSyntax> usings, ImmutableHashSet<string>.Builder builder) { foreach (var @using in usings) { if (@using.Alias == null || @using.Alias.Name == null) { continue; } @using.Alias.Name.Identifier.ValueText.AppendToAliasNameSet(builder); } } private void AppendAliasNames(IEnumerable<BaseNamespaceDeclarationSyntax> namespaces, ImmutableHashSet<string>.Builder builder, CancellationToken cancellationToken) { foreach (var @namespace in namespaces) { cancellationToken.ThrowIfCancellationRequested(); AppendAliasNames(@namespace.Usings, builder); AppendAliasNames(@namespace.Members.OfType<BaseNamespaceDeclarationSyntax>(), builder, cancellationToken); } } public ForEachSymbols GetForEachSymbols(SemanticModel semanticModel, SyntaxNode forEachStatement) { if (forEachStatement is CommonForEachStatementSyntax csforEachStatement) { var info = semanticModel.GetForEachStatementInfo(csforEachStatement); return new ForEachSymbols( info.GetEnumeratorMethod, info.MoveNextMethod, info.CurrentProperty, info.DisposeMethod, info.ElementType); } else { return default; } } public IMethodSymbol GetGetAwaiterMethod(SemanticModel semanticModel, SyntaxNode node) { if (node is AwaitExpressionSyntax awaitExpression) { var info = semanticModel.GetAwaitExpressionInfo(awaitExpression); return info.GetAwaiterMethod; } return null; } public ImmutableArray<IMethodSymbol> GetDeconstructionAssignmentMethods(SemanticModel semanticModel, SyntaxNode node) { if (node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction()) { using var builder = TemporaryArray<IMethodSymbol>.Empty; FlattenDeconstructionMethods(semanticModel.GetDeconstructionInfo(assignment), ref builder.AsRef()); return builder.ToImmutableAndClear(); } return ImmutableArray<IMethodSymbol>.Empty; } public ImmutableArray<IMethodSymbol> GetDeconstructionForEachMethods(SemanticModel semanticModel, SyntaxNode node) { if (node is ForEachVariableStatementSyntax @foreach) { using var builder = TemporaryArray<IMethodSymbol>.Empty; FlattenDeconstructionMethods(semanticModel.GetDeconstructionInfo(@foreach), ref builder.AsRef()); return builder.ToImmutableAndClear(); } return ImmutableArray<IMethodSymbol>.Empty; } private static void FlattenDeconstructionMethods(DeconstructionInfo deconstruction, ref TemporaryArray<IMethodSymbol> builder) { var method = deconstruction.Method; if (method != null) { builder.Add(method); } foreach (var nested in deconstruction.Nested) { FlattenDeconstructionMethods(nested, ref builder); } } public bool IsPartial(ITypeSymbol typeSymbol, CancellationToken cancellationToken) { var syntaxRefs = typeSymbol.DeclaringSyntaxReferences; return syntaxRefs.Any(static (n, cancellationToken) => ((BaseTypeDeclarationSyntax)n.GetSyntax(cancellationToken)).Modifiers.Any(SyntaxKind.PartialKeyword), cancellationToken); } public IEnumerable<ISymbol> GetDeclaredSymbols( SemanticModel semanticModel, SyntaxNode memberDeclaration, CancellationToken cancellationToken) { switch (memberDeclaration) { case FieldDeclarationSyntax field: return field.Declaration.Variables.Select( v => semanticModel.GetDeclaredSymbol(v, cancellationToken)); case EventFieldDeclarationSyntax eventField: return eventField.Declaration.Variables.Select( v => semanticModel.GetDeclaredSymbol(v, cancellationToken)); default: return SpecializedCollections.SingletonEnumerable( semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken)); } } public IParameterSymbol FindParameterForArgument(SemanticModel semanticModel, SyntaxNode argument, bool allowUncertainCandidates, CancellationToken cancellationToken) => ((ArgumentSyntax)argument).DetermineParameter(semanticModel, allowUncertainCandidates, allowParams: false, cancellationToken); public IParameterSymbol FindParameterForAttributeArgument(SemanticModel semanticModel, SyntaxNode argument, bool allowUncertainCandidates, CancellationToken cancellationToken) => ((AttributeArgumentSyntax)argument).DetermineParameter(semanticModel, allowUncertainCandidates, allowParams: false, cancellationToken); // Normal arguments can't reference fields/properties in c# public ISymbol FindFieldOrPropertyForArgument(SemanticModel semanticModel, SyntaxNode argument, CancellationToken cancellationToken) => null; public ISymbol FindFieldOrPropertyForAttributeArgument(SemanticModel semanticModel, SyntaxNode argument, CancellationToken cancellationToken) => argument is AttributeArgumentSyntax { NameEquals.Name: var name } ? semanticModel.GetSymbolInfo(name, cancellationToken).GetAnySymbol() : null; public ImmutableArray<ISymbol> GetBestOrAllSymbols(SemanticModel semanticModel, SyntaxNode node, SyntaxToken token, CancellationToken cancellationToken) { if (node == null) return ImmutableArray<ISymbol>.Empty; return node switch { AssignmentExpressionSyntax _ when token.Kind() == SyntaxKind.EqualsToken => GetDeconstructionAssignmentMethods(semanticModel, node).As<ISymbol>(), ForEachVariableStatementSyntax _ when token.Kind() == SyntaxKind.InKeyword => GetDeconstructionForEachMethods(semanticModel, node).As<ISymbol>(), _ => GetSymbolInfo(semanticModel, node, token, cancellationToken).GetBestOrAllSymbols(), }; } private static SymbolInfo GetSymbolInfo(SemanticModel semanticModel, SyntaxNode node, SyntaxToken token, CancellationToken cancellationToken) { switch (node) { case OrderByClauseSyntax orderByClauseSyntax: if (token.Kind() == SyntaxKind.CommaToken) { // Returning SymbolInfo for a comma token is the last resort // in an order by clause if no other tokens to bind to a are present. // See also the proposal at https://github.com/dotnet/roslyn/issues/23394 var separators = orderByClauseSyntax.Orderings.GetSeparators().ToImmutableList(); var index = separators.IndexOf(token); if (index >= 0 && (index + 1) < orderByClauseSyntax.Orderings.Count) { var ordering = orderByClauseSyntax.Orderings[index + 1]; if (ordering.AscendingOrDescendingKeyword.Kind() == SyntaxKind.None) { return semanticModel.GetSymbolInfo(ordering, cancellationToken); } } } else if (orderByClauseSyntax.Orderings[0].AscendingOrDescendingKeyword.Kind() == SyntaxKind.None) { // The first ordering is displayed on the "orderby" keyword itself if there isn't a // ascending/descending keyword. return semanticModel.GetSymbolInfo(orderByClauseSyntax.Orderings[0], cancellationToken); } return default; case QueryClauseSyntax queryClauseSyntax: var queryInfo = semanticModel.GetQueryClauseInfo(queryClauseSyntax, cancellationToken); var hasCastInfo = queryInfo.CastInfo.Symbol != null; var hasOperationInfo = queryInfo.OperationInfo.Symbol != null; if (hasCastInfo && hasOperationInfo) { // In some cases a single clause binds to more than one method. In those cases // the tokens in the clause determine which of the two SymbolInfos are returned. // See also the proposal at https://github.com/dotnet/roslyn/issues/23394 return token.IsKind(SyntaxKind.InKeyword) ? queryInfo.CastInfo : queryInfo.OperationInfo; } if (hasCastInfo) { return queryInfo.CastInfo; } return queryInfo.OperationInfo; case IdentifierNameSyntax { Parent: PrimaryConstructorBaseTypeSyntax baseType }: return semanticModel.GetSymbolInfo(baseType, cancellationToken); } //Only in the orderby clause a comma can bind to a symbol. if (token.IsKind(SyntaxKind.CommaToken)) { return default; } return semanticModel.GetSymbolInfo(node, cancellationToken); } public bool IsInsideNameOfExpression(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => (node as ExpressionSyntax).IsInsideNameOfExpression(semanticModel, cancellationToken); public ImmutableArray<IMethodSymbol> GetLocalFunctionSymbols(Compilation compilation, ISymbol symbol, CancellationToken cancellationToken) { using var _ = ArrayBuilder<IMethodSymbol>.GetInstance(out var builder); foreach (var syntaxReference in symbol.DeclaringSyntaxReferences) { var semanticModel = compilation.GetSemanticModel(syntaxReference.SyntaxTree); var node = syntaxReference.GetSyntax(cancellationToken); foreach (var localFunction in node.DescendantNodes().Where(CSharpSyntaxFacts.Instance.IsLocalFunctionStatement)) { var localFunctionSymbol = semanticModel.GetDeclaredSymbol(localFunction, cancellationToken); if (localFunctionSymbol is IMethodSymbol methodSymbol) { builder.Add(methodSymbol); } } } return builder.ToImmutable(); } public bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol expressionTypeOpt, CancellationToken cancellationToken) => node.IsInExpressionTree(semanticModel, expressionTypeOpt, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class CSharpSemanticFacts : ISemanticFacts { internal static readonly CSharpSemanticFacts Instance = new(); private CSharpSemanticFacts() { } public ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; public bool SupportsImplicitInterfaceImplementation => true; public bool ExposesAnonymousFunctionParameterNames => false; public bool IsWrittenTo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => (node as ExpressionSyntax).IsWrittenTo(semanticModel, cancellationToken); public bool IsOnlyWrittenTo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => (node as ExpressionSyntax).IsOnlyWrittenTo(); public bool IsInOutContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => (node as ExpressionSyntax).IsInOutContext(); public bool IsInRefContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => (node as ExpressionSyntax).IsInRefContext(); public bool IsInInContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => (node as ExpressionSyntax).IsInInContext(); public bool CanReplaceWithRValue(SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken) => (expression as ExpressionSyntax).CanReplaceWithRValue(semanticModel, cancellationToken); public ISymbol GetDeclaredSymbol(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { var location = token.GetLocation(); foreach (var ancestor in token.GetAncestors<SyntaxNode>()) { var symbol = semanticModel.GetDeclaredSymbol(ancestor, cancellationToken); if (symbol != null) { if (symbol is IMethodSymbol { MethodKind: MethodKind.Conversion }) { // The token may be part of a larger name (for example, `int` in `public static operator int[](Goo g);`. // So check if the symbol's location encompasses the span of the token we're asking about. if (symbol.Locations.Any(static (loc, location) => loc.SourceTree == location.SourceTree && loc.SourceSpan.Contains(location.SourceSpan), location)) return symbol; } else { // For any other symbols, we only care if the name directly matches the span of the token if (symbol.Locations.Contains(location)) return symbol; } // We found some symbol, but it defined something else. We're not going to have a higher node defining _another_ symbol with this token, so we can stop now. return null; } // If we hit an executable statement syntax and didn't find anything yet, we can just stop now -- anything higher would be a member declaration which won't be defined by something inside a statement. if (CSharpSyntaxFacts.Instance.IsExecutableStatement(ancestor)) { return null; } } return null; } public bool LastEnumValueHasInitializer(INamedTypeSymbol namedTypeSymbol) { var enumDecl = namedTypeSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).OfType<EnumDeclarationSyntax>().FirstOrDefault(); if (enumDecl != null) { var lastMember = enumDecl.Members.LastOrDefault(); if (lastMember != null) { return lastMember.EqualsValue != null; } } return false; } public bool SupportsParameterizedProperties => false; public bool TryGetSpeculativeSemanticModel(SemanticModel oldSemanticModel, SyntaxNode oldNode, SyntaxNode newNode, out SemanticModel speculativeModel) { Debug.Assert(oldNode.Kind() == newNode.Kind()); var model = oldSemanticModel; if (oldNode is not BaseMethodDeclarationSyntax oldMethod || newNode is not BaseMethodDeclarationSyntax newMethod || oldMethod.Body == null) { speculativeModel = null; return false; } var success = model.TryGetSpeculativeSemanticModelForMethodBody(oldMethod.Body.OpenBraceToken.Span.End, newMethod, out var csharpModel); speculativeModel = csharpModel; return success; } public ImmutableHashSet<string> GetAliasNameSet(SemanticModel model, CancellationToken cancellationToken) { var original = model.GetOriginalSemanticModel(); if (!original.SyntaxTree.HasCompilationUnitRoot) { return ImmutableHashSet.Create<string>(); } var root = original.SyntaxTree.GetCompilationUnitRoot(cancellationToken); var builder = ImmutableHashSet.CreateBuilder<string>(StringComparer.Ordinal); AppendAliasNames(root.Usings, builder); AppendAliasNames(root.Members.OfType<BaseNamespaceDeclarationSyntax>(), builder, cancellationToken); return builder.ToImmutable(); } private static void AppendAliasNames(SyntaxList<UsingDirectiveSyntax> usings, ImmutableHashSet<string>.Builder builder) { foreach (var @using in usings) { if (@using.Alias == null || @using.Alias.Name == null) { continue; } @using.Alias.Name.Identifier.ValueText.AppendToAliasNameSet(builder); } } private void AppendAliasNames(IEnumerable<BaseNamespaceDeclarationSyntax> namespaces, ImmutableHashSet<string>.Builder builder, CancellationToken cancellationToken) { foreach (var @namespace in namespaces) { cancellationToken.ThrowIfCancellationRequested(); AppendAliasNames(@namespace.Usings, builder); AppendAliasNames(@namespace.Members.OfType<BaseNamespaceDeclarationSyntax>(), builder, cancellationToken); } } public ForEachSymbols GetForEachSymbols(SemanticModel semanticModel, SyntaxNode forEachStatement) { if (forEachStatement is CommonForEachStatementSyntax csforEachStatement) { var info = semanticModel.GetForEachStatementInfo(csforEachStatement); return new ForEachSymbols( info.GetEnumeratorMethod, info.MoveNextMethod, info.CurrentProperty, info.DisposeMethod, info.ElementType); } else { return default; } } public IMethodSymbol GetGetAwaiterMethod(SemanticModel semanticModel, SyntaxNode node) { if (node is AwaitExpressionSyntax awaitExpression) { var info = semanticModel.GetAwaitExpressionInfo(awaitExpression); return info.GetAwaiterMethod; } return null; } public ImmutableArray<IMethodSymbol> GetDeconstructionAssignmentMethods(SemanticModel semanticModel, SyntaxNode node) { if (node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction()) { using var builder = TemporaryArray<IMethodSymbol>.Empty; FlattenDeconstructionMethods(semanticModel.GetDeconstructionInfo(assignment), ref builder.AsRef()); return builder.ToImmutableAndClear(); } return ImmutableArray<IMethodSymbol>.Empty; } public ImmutableArray<IMethodSymbol> GetDeconstructionForEachMethods(SemanticModel semanticModel, SyntaxNode node) { if (node is ForEachVariableStatementSyntax @foreach) { using var builder = TemporaryArray<IMethodSymbol>.Empty; FlattenDeconstructionMethods(semanticModel.GetDeconstructionInfo(@foreach), ref builder.AsRef()); return builder.ToImmutableAndClear(); } return ImmutableArray<IMethodSymbol>.Empty; } private static void FlattenDeconstructionMethods(DeconstructionInfo deconstruction, ref TemporaryArray<IMethodSymbol> builder) { var method = deconstruction.Method; if (method != null) { builder.Add(method); } foreach (var nested in deconstruction.Nested) { FlattenDeconstructionMethods(nested, ref builder); } } public bool IsPartial(ITypeSymbol typeSymbol, CancellationToken cancellationToken) { var syntaxRefs = typeSymbol.DeclaringSyntaxReferences; return syntaxRefs.Any(static (n, cancellationToken) => ((BaseTypeDeclarationSyntax)n.GetSyntax(cancellationToken)).Modifiers.Any(SyntaxKind.PartialKeyword), cancellationToken); } public IEnumerable<ISymbol> GetDeclaredSymbols( SemanticModel semanticModel, SyntaxNode memberDeclaration, CancellationToken cancellationToken) { switch (memberDeclaration) { case FieldDeclarationSyntax field: return field.Declaration.Variables.Select( v => semanticModel.GetDeclaredSymbol(v, cancellationToken)); case EventFieldDeclarationSyntax eventField: return eventField.Declaration.Variables.Select( v => semanticModel.GetDeclaredSymbol(v, cancellationToken)); default: return SpecializedCollections.SingletonEnumerable( semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken)); } } public IParameterSymbol FindParameterForArgument(SemanticModel semanticModel, SyntaxNode argument, bool allowUncertainCandidates, CancellationToken cancellationToken) => ((ArgumentSyntax)argument).DetermineParameter(semanticModel, allowUncertainCandidates, allowParams: false, cancellationToken); public IParameterSymbol FindParameterForAttributeArgument(SemanticModel semanticModel, SyntaxNode argument, bool allowUncertainCandidates, CancellationToken cancellationToken) => ((AttributeArgumentSyntax)argument).DetermineParameter(semanticModel, allowUncertainCandidates, allowParams: false, cancellationToken); // Normal arguments can't reference fields/properties in c# public ISymbol FindFieldOrPropertyForArgument(SemanticModel semanticModel, SyntaxNode argument, CancellationToken cancellationToken) => null; public ISymbol FindFieldOrPropertyForAttributeArgument(SemanticModel semanticModel, SyntaxNode argument, CancellationToken cancellationToken) => argument is AttributeArgumentSyntax { NameEquals.Name: var name } ? semanticModel.GetSymbolInfo(name, cancellationToken).GetAnySymbol() : null; public ImmutableArray<ISymbol> GetBestOrAllSymbols(SemanticModel semanticModel, SyntaxNode node, SyntaxToken token, CancellationToken cancellationToken) { if (node == null) return ImmutableArray<ISymbol>.Empty; return node switch { AssignmentExpressionSyntax _ when token.Kind() == SyntaxKind.EqualsToken => GetDeconstructionAssignmentMethods(semanticModel, node).As<ISymbol>(), ForEachVariableStatementSyntax _ when token.Kind() == SyntaxKind.InKeyword => GetDeconstructionForEachMethods(semanticModel, node).As<ISymbol>(), _ => GetSymbolInfo(semanticModel, node, token, cancellationToken).GetBestOrAllSymbols(), }; } private static SymbolInfo GetSymbolInfo(SemanticModel semanticModel, SyntaxNode node, SyntaxToken token, CancellationToken cancellationToken) { switch (node) { case OrderByClauseSyntax orderByClauseSyntax: if (token.Kind() == SyntaxKind.CommaToken) { // Returning SymbolInfo for a comma token is the last resort // in an order by clause if no other tokens to bind to a are present. // See also the proposal at https://github.com/dotnet/roslyn/issues/23394 var separators = orderByClauseSyntax.Orderings.GetSeparators().ToImmutableList(); var index = separators.IndexOf(token); if (index >= 0 && (index + 1) < orderByClauseSyntax.Orderings.Count) { var ordering = orderByClauseSyntax.Orderings[index + 1]; if (ordering.AscendingOrDescendingKeyword.Kind() == SyntaxKind.None) { return semanticModel.GetSymbolInfo(ordering, cancellationToken); } } } else if (orderByClauseSyntax.Orderings[0].AscendingOrDescendingKeyword.Kind() == SyntaxKind.None) { // The first ordering is displayed on the "orderby" keyword itself if there isn't a // ascending/descending keyword. return semanticModel.GetSymbolInfo(orderByClauseSyntax.Orderings[0], cancellationToken); } return default; case QueryClauseSyntax queryClauseSyntax: var queryInfo = semanticModel.GetQueryClauseInfo(queryClauseSyntax, cancellationToken); var hasCastInfo = queryInfo.CastInfo.Symbol != null; var hasOperationInfo = queryInfo.OperationInfo.Symbol != null; if (hasCastInfo && hasOperationInfo) { // In some cases a single clause binds to more than one method. In those cases // the tokens in the clause determine which of the two SymbolInfos are returned. // See also the proposal at https://github.com/dotnet/roslyn/issues/23394 return token.IsKind(SyntaxKind.InKeyword) ? queryInfo.CastInfo : queryInfo.OperationInfo; } if (hasCastInfo) { return queryInfo.CastInfo; } return queryInfo.OperationInfo; case IdentifierNameSyntax { Parent: PrimaryConstructorBaseTypeSyntax baseType }: return semanticModel.GetSymbolInfo(baseType, cancellationToken); } //Only in the orderby clause a comma can bind to a symbol. if (token.IsKind(SyntaxKind.CommaToken)) { return default; } return semanticModel.GetSymbolInfo(node, cancellationToken); } public bool IsInsideNameOfExpression(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => (node as ExpressionSyntax).IsInsideNameOfExpression(semanticModel, cancellationToken); public ImmutableArray<IMethodSymbol> GetLocalFunctionSymbols(Compilation compilation, ISymbol symbol, CancellationToken cancellationToken) { using var _ = ArrayBuilder<IMethodSymbol>.GetInstance(out var builder); foreach (var syntaxReference in symbol.DeclaringSyntaxReferences) { var semanticModel = compilation.GetSemanticModel(syntaxReference.SyntaxTree); var node = syntaxReference.GetSyntax(cancellationToken); foreach (var localFunction in node.DescendantNodes().Where(CSharpSyntaxFacts.Instance.IsLocalFunctionStatement)) { var localFunctionSymbol = semanticModel.GetDeclaredSymbol(localFunction, cancellationToken); if (localFunctionSymbol is IMethodSymbol methodSymbol) { builder.Add(methodSymbol); } } } return builder.ToImmutable(); } public bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol expressionTypeOpt, CancellationToken cancellationToken) => node.IsInExpressionTree(semanticModel, expressionTypeOpt, cancellationToken); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedDelegateSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedDelegateConstructor : SynthesizedInstanceConstructor { private readonly ImmutableArray<ParameterSymbol> _parameters; public SynthesizedDelegateConstructor(NamedTypeSymbol containingType, TypeSymbol objectType, TypeSymbol intPtrType) : base(containingType) { _parameters = ImmutableArray.Create<ParameterSymbol>( SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(objectType), 0, RefKind.None, "object"), SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(intPtrType), 1, RefKind.None, "method")); } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } } internal sealed class SynthesizedDelegateInvokeMethod : SynthesizedInstanceMethodSymbol { private readonly NamedTypeSymbol _containingType; internal SynthesizedDelegateInvokeMethod(NamedTypeSymbol containingType, ArrayBuilder<(TypeWithAnnotations Type, RefKind RefKind, DeclarationScope Scope)> parameterDescriptions, TypeWithAnnotations returnType, RefKind refKind) { _containingType = containingType; Parameters = parameterDescriptions.SelectAsArrayWithIndex((p, i, m) => SynthesizedParameterSymbol.Create(m, p.Type, i, p.RefKind, scope: p.Scope), this); ReturnTypeWithAnnotations = returnType; RefKind = refKind; } public override string Name { get { return WellKnownMemberNames.DelegateInvokeName; } } internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return true; } internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return true; } internal override bool IsMetadataFinal { get { return false; } } public override MethodKind MethodKind { get { return MethodKind.DelegateInvoke; } } public override int Arity { get { return 0; } } public override bool IsExtensionMethod { get { return false; } } internal override bool HasSpecialName { get { return false; } } internal override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return System.Reflection.MethodImplAttributes.Runtime; } } internal override bool HasDeclarativeSecurity { get { return false; } } public override DllImportData? GetDllImportData() { return null; } internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation { get { return null; } } internal override bool RequiresSecurityObject { get { return false; } } public override bool HidesBaseMethodsByName { get { return false; } } public override bool IsVararg { get { return false; } } public override bool ReturnsVoid { get { return ReturnType.IsVoidType(); } } public override bool IsAsync { get { return false; } } public override RefKind RefKind { get; } public override TypeWithAnnotations ReturnTypeWithAnnotations { get; } public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations { get { return ImmutableArray<TypeWithAnnotations>.Empty; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public override ImmutableArray<ParameterSymbol> Parameters { get; } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override Symbol? AssociatedSymbol { get { return null; } } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { return ImmutableArray<string>.Empty; } internal override Microsoft.Cci.CallingConvention CallingConvention { get { return Microsoft.Cci.CallingConvention.HasThis; } } internal override bool GenerateDebugInfo { get { return false; } } public override Symbol ContainingSymbol { get { return _containingType; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override Accessibility DeclaredAccessibility { get { // Invoke method of a delegate used in a dynamic call-site must be public // since the DLR looks only for public Invoke methods: return Accessibility.Public; } } public override bool IsStatic { get { return false; } } public override bool IsVirtual { get { return true; } } public override bool IsOverride { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsSealed { get { return false; } } public override bool IsExtern { get { return false; } } protected sealed override bool HasSetsRequiredMembersImpl => throw ExceptionUtilities.Unreachable; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedDelegateConstructor : SynthesizedInstanceConstructor { private readonly ImmutableArray<ParameterSymbol> _parameters; public SynthesizedDelegateConstructor(NamedTypeSymbol containingType, TypeSymbol objectType, TypeSymbol intPtrType) : base(containingType) { _parameters = ImmutableArray.Create<ParameterSymbol>( SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(objectType), 0, RefKind.None, "object"), SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(intPtrType), 1, RefKind.None, "method")); } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } } internal sealed class SynthesizedDelegateInvokeMethod : SynthesizedInstanceMethodSymbol { private readonly NamedTypeSymbol _containingType; internal SynthesizedDelegateInvokeMethod(NamedTypeSymbol containingType, ArrayBuilder<(TypeWithAnnotations Type, RefKind RefKind, DeclarationScope Scope)> parameterDescriptions, TypeWithAnnotations returnType, RefKind refKind) { _containingType = containingType; Parameters = parameterDescriptions.SelectAsArrayWithIndex((p, i, m) => SynthesizedParameterSymbol.Create(m, p.Type, i, p.RefKind, scope: p.Scope), this); ReturnTypeWithAnnotations = returnType; RefKind = refKind; } public override string Name { get { return WellKnownMemberNames.DelegateInvokeName; } } internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return true; } internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return true; } internal override bool IsMetadataFinal { get { return false; } } public override MethodKind MethodKind { get { return MethodKind.DelegateInvoke; } } public override int Arity { get { return 0; } } public override bool IsExtensionMethod { get { return false; } } internal override bool HasSpecialName { get { return false; } } internal override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return System.Reflection.MethodImplAttributes.Runtime; } } internal override bool HasDeclarativeSecurity { get { return false; } } public override DllImportData? GetDllImportData() { return null; } internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation { get { return null; } } internal override bool RequiresSecurityObject { get { return false; } } public override bool HidesBaseMethodsByName { get { return false; } } public override bool IsVararg { get { return false; } } public override bool ReturnsVoid { get { return ReturnType.IsVoidType(); } } public override bool IsAsync { get { return false; } } public override RefKind RefKind { get; } public override TypeWithAnnotations ReturnTypeWithAnnotations { get; } public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations { get { return ImmutableArray<TypeWithAnnotations>.Empty; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public override ImmutableArray<ParameterSymbol> Parameters { get; } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override Symbol? AssociatedSymbol { get { return null; } } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { return ImmutableArray<string>.Empty; } internal override Microsoft.Cci.CallingConvention CallingConvention { get { return Microsoft.Cci.CallingConvention.HasThis; } } internal override bool GenerateDebugInfo { get { return false; } } public override Symbol ContainingSymbol { get { return _containingType; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override Accessibility DeclaredAccessibility { get { // Invoke method of a delegate used in a dynamic call-site must be public // since the DLR looks only for public Invoke methods: return Accessibility.Public; } } public override bool IsStatic { get { return false; } } public override bool IsVirtual { get { return true; } } public override bool IsOverride { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsSealed { get { return false; } } public override bool IsExtern { get { return false; } } protected sealed override bool HasSetsRequiredMembersImpl => throw ExceptionUtilities.Unreachable; } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrDebuggerTypeProxyAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using Microsoft.VisualStudio.Debugger.Clr; namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { public class DkmClrDebuggerTypeProxyAttribute : DkmClrEvalAttribute { internal DkmClrDebuggerTypeProxyAttribute(DkmClrType proxyType) : base(null) { this.ProxyType = proxyType; } public readonly DkmClrType ProxyType; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using Microsoft.VisualStudio.Debugger.Clr; namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { public class DkmClrDebuggerTypeProxyAttribute : DkmClrEvalAttribute { internal DkmClrDebuggerTypeProxyAttribute(DkmClrType proxyType) : base(null) { this.ProxyType = proxyType; } public readonly DkmClrType ProxyType; } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Xaml/Impl/Features/AutoInsert/XamlAutoInsertResult.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.AutoInsert { internal class XamlAutoInsertResult { public TextChange TextChange { get; set; } public int? CaretOffset { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.AutoInsert { internal class XamlAutoInsertResult { public TextChange TextChange { get; set; } public int? CaretOffset { get; set; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Test/CodeModel/AbstractCodeEventTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports EnvDTE80 Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractCodeEventTests Inherits AbstractCodeElementTests(Of EnvDTE80.CodeEvent) Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE80.CodeEvent) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetStartPoint(part) End Function Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE80.CodeEvent) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetEndPoint(part) End Function Protected Overrides Function GetAccess(codeElement As EnvDTE80.CodeEvent) As EnvDTE.vsCMAccess Return codeElement.Access End Function Protected Overrides Function GetAttributes(codeElement As EnvDTE80.CodeEvent) As EnvDTE.CodeElements Return codeElement.Attributes End Function Protected Overrides Function GetComment(codeElement As EnvDTE80.CodeEvent) As String Return codeElement.Comment End Function Protected Overrides Function GetDocComment(codeElement As EnvDTE80.CodeEvent) As String Return codeElement.DocComment End Function Protected Overrides Function GetFullName(codeElement As EnvDTE80.CodeEvent) As String Return codeElement.FullName End Function Protected Overrides Function GetIsShared(codeElement As EnvDTE80.CodeEvent) As Boolean Return codeElement.IsShared End Function Protected Overrides Function GetIsSharedSetter(codeElement As EnvDTE80.CodeEvent) As Action(Of Boolean) Return Sub(value) codeElement.IsShared = value End Function Protected Overrides Function GetKind(codeElement As EnvDTE80.CodeEvent) As EnvDTE.vsCMElement Return codeElement.Kind End Function Protected Overrides Function GetName(codeElement As EnvDTE80.CodeEvent) As String Return codeElement.Name End Function Protected Overrides Function GetNameSetter(codeElement As EnvDTE80.CodeEvent) As Action(Of String) Return Sub(name) codeElement.Name = name End Function Protected Overrides Function GetOverrideKind(codeElement As CodeEvent) As vsCMOverrideKind Return codeElement.OverrideKind End Function Protected Overrides Function GetParent(codeElement As EnvDTE80.CodeEvent) As Object Return codeElement.Parent End Function Protected Overrides Function GetPrototype(codeElement As EnvDTE80.CodeEvent, flags As EnvDTE.vsCMPrototype) As String Return codeElement.Prototype(flags) End Function Protected Overrides Function GetTypeProp(codeElement As EnvDTE80.CodeEvent) As EnvDTE.CodeTypeRef Return codeElement.Type End Function Protected Overrides Function GetTypePropSetter(codeElement As EnvDTE80.CodeEvent) As Action(Of EnvDTE.CodeTypeRef) Return Sub(value) codeElement.Type = value End Function Protected Overrides Function AddAttribute(codeElement As EnvDTE80.CodeEvent, data As AttributeData) As EnvDTE.CodeAttribute Return codeElement.AddAttribute(data.Name, data.Value, data.Position) End Function Protected Sub TestIsPropertyStyleEvent(code As XElement, expected As Boolean) TestElement(code, Sub(codeElement) Assert.Equal(expected, codeElement.IsPropertyStyleEvent) End Sub) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports EnvDTE80 Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractCodeEventTests Inherits AbstractCodeElementTests(Of EnvDTE80.CodeEvent) Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE80.CodeEvent) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetStartPoint(part) End Function Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE80.CodeEvent) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetEndPoint(part) End Function Protected Overrides Function GetAccess(codeElement As EnvDTE80.CodeEvent) As EnvDTE.vsCMAccess Return codeElement.Access End Function Protected Overrides Function GetAttributes(codeElement As EnvDTE80.CodeEvent) As EnvDTE.CodeElements Return codeElement.Attributes End Function Protected Overrides Function GetComment(codeElement As EnvDTE80.CodeEvent) As String Return codeElement.Comment End Function Protected Overrides Function GetDocComment(codeElement As EnvDTE80.CodeEvent) As String Return codeElement.DocComment End Function Protected Overrides Function GetFullName(codeElement As EnvDTE80.CodeEvent) As String Return codeElement.FullName End Function Protected Overrides Function GetIsShared(codeElement As EnvDTE80.CodeEvent) As Boolean Return codeElement.IsShared End Function Protected Overrides Function GetIsSharedSetter(codeElement As EnvDTE80.CodeEvent) As Action(Of Boolean) Return Sub(value) codeElement.IsShared = value End Function Protected Overrides Function GetKind(codeElement As EnvDTE80.CodeEvent) As EnvDTE.vsCMElement Return codeElement.Kind End Function Protected Overrides Function GetName(codeElement As EnvDTE80.CodeEvent) As String Return codeElement.Name End Function Protected Overrides Function GetNameSetter(codeElement As EnvDTE80.CodeEvent) As Action(Of String) Return Sub(name) codeElement.Name = name End Function Protected Overrides Function GetOverrideKind(codeElement As CodeEvent) As vsCMOverrideKind Return codeElement.OverrideKind End Function Protected Overrides Function GetParent(codeElement As EnvDTE80.CodeEvent) As Object Return codeElement.Parent End Function Protected Overrides Function GetPrototype(codeElement As EnvDTE80.CodeEvent, flags As EnvDTE.vsCMPrototype) As String Return codeElement.Prototype(flags) End Function Protected Overrides Function GetTypeProp(codeElement As EnvDTE80.CodeEvent) As EnvDTE.CodeTypeRef Return codeElement.Type End Function Protected Overrides Function GetTypePropSetter(codeElement As EnvDTE80.CodeEvent) As Action(Of EnvDTE.CodeTypeRef) Return Sub(value) codeElement.Type = value End Function Protected Overrides Function AddAttribute(codeElement As EnvDTE80.CodeEvent, data As AttributeData) As EnvDTE.CodeAttribute Return codeElement.AddAttribute(data.Name, data.Value, data.Position) End Function Protected Sub TestIsPropertyStyleEvent(code As XElement, expected As Boolean) TestElement(code, Sub(codeElement) Assert.Equal(expected, codeElement.IsPropertyStyleEvent) End Sub) End Sub End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/CSharpTest/EditAndContinue/Helpers/EditAndContinueValidation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.Contracts; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { internal static class EditAndContinueValidation { internal static void VerifyLineEdits( this EditScript<SyntaxNode> editScript, SourceLineUpdate[] lineEdits, SemanticEditDescription[]? semanticEdits = null, RudeEditDiagnosticDescription[]? diagnostics = null, EditAndContinueCapabilities? capabilities = null) { Assert.NotEmpty(lineEdits); VerifyLineEdits( editScript, new[] { new SequencePointUpdates(editScript.Match.OldRoot.SyntaxTree.FilePath, lineEdits.ToImmutableArray()) }, semanticEdits, diagnostics, capabilities); } internal static void VerifyLineEdits( this EditScript<SyntaxNode> editScript, SequencePointUpdates[] lineEdits, SemanticEditDescription[]? semanticEdits = null, RudeEditDiagnosticDescription[]? diagnostics = null, EditAndContinueCapabilities? capabilities = null) { new CSharpEditAndContinueTestHelpers().VerifyLineEdits( editScript, lineEdits, semanticEdits, diagnostics, capabilities); } internal static void VerifySemanticDiagnostics( this EditScript<SyntaxNode> editScript, params RudeEditDiagnosticDescription[] diagnostics) { VerifySemanticDiagnostics(editScript, activeStatements: null, targetFrameworks: null, capabilities: null, diagnostics); } internal static void VerifySemanticDiagnostics( this EditScript<SyntaxNode> editScript, ActiveStatementsDescription activeStatements, params RudeEditDiagnosticDescription[] diagnostics) { VerifySemanticDiagnostics(editScript, activeStatements, targetFrameworks: null, capabilities: null, diagnostics); } internal static void VerifySemanticDiagnostics( this EditScript<SyntaxNode> editScript, RudeEditDiagnosticDescription[] diagnostics, EditAndContinueCapabilities? capabilities) { VerifySemanticDiagnostics(editScript, activeStatements: null, targetFrameworks: null, capabilities, diagnostics); } internal static void VerifySemanticDiagnostics( this EditScript<SyntaxNode> editScript, ActiveStatementsDescription? activeStatements = null, TargetFramework[]? targetFrameworks = null, EditAndContinueCapabilities? capabilities = null, params RudeEditDiagnosticDescription[] diagnostics) { VerifySemantics( new[] { editScript }, new[] { new DocumentAnalysisResultsDescription(activeStatements: activeStatements, diagnostics: diagnostics) }, targetFrameworks, capabilities); } internal static void VerifySemantics( this EditScript<SyntaxNode> editScript, ActiveStatementsDescription activeStatements, SemanticEditDescription[] semanticEdits, EditAndContinueCapabilities? capabilities = null) { VerifySemantics( new[] { editScript }, new[] { new DocumentAnalysisResultsDescription(activeStatements, semanticEdits: semanticEdits) }, capabilities: capabilities); } internal static void VerifySemantics( this EditScript<SyntaxNode> editScript, SemanticEditDescription[] semanticEdits, EditAndContinueCapabilities capabilities) { VerifySemantics(editScript, ActiveStatementsDescription.Empty, semanticEdits, capabilities); } internal static void VerifySemantics( this EditScript<SyntaxNode> editScript, params SemanticEditDescription[] semanticEdits) { VerifySemantics(editScript, ActiveStatementsDescription.Empty, semanticEdits, capabilities: null); } internal static void VerifySemantics( EditScript<SyntaxNode>[] editScripts, DocumentAnalysisResultsDescription[] results, TargetFramework[]? targetFrameworks = null, EditAndContinueCapabilities? capabilities = null) { foreach (var targetFramework in targetFrameworks ?? new[] { TargetFramework.NetStandard20, TargetFramework.NetCoreApp }) { new CSharpEditAndContinueTestHelpers().VerifySemantics(editScripts, targetFramework, results, capabilities); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.Contracts; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { internal static class EditAndContinueValidation { internal static void VerifyLineEdits( this EditScript<SyntaxNode> editScript, SourceLineUpdate[] lineEdits, SemanticEditDescription[]? semanticEdits = null, RudeEditDiagnosticDescription[]? diagnostics = null, EditAndContinueCapabilities? capabilities = null) { Assert.NotEmpty(lineEdits); VerifyLineEdits( editScript, new[] { new SequencePointUpdates(editScript.Match.OldRoot.SyntaxTree.FilePath, lineEdits.ToImmutableArray()) }, semanticEdits, diagnostics, capabilities); } internal static void VerifyLineEdits( this EditScript<SyntaxNode> editScript, SequencePointUpdates[] lineEdits, SemanticEditDescription[]? semanticEdits = null, RudeEditDiagnosticDescription[]? diagnostics = null, EditAndContinueCapabilities? capabilities = null) { new CSharpEditAndContinueTestHelpers().VerifyLineEdits( editScript, lineEdits, semanticEdits, diagnostics, capabilities); } internal static void VerifySemanticDiagnostics( this EditScript<SyntaxNode> editScript, params RudeEditDiagnosticDescription[] diagnostics) { VerifySemanticDiagnostics(editScript, activeStatements: null, targetFrameworks: null, capabilities: null, diagnostics); } internal static void VerifySemanticDiagnostics( this EditScript<SyntaxNode> editScript, ActiveStatementsDescription activeStatements, params RudeEditDiagnosticDescription[] diagnostics) { VerifySemanticDiagnostics(editScript, activeStatements, targetFrameworks: null, capabilities: null, diagnostics); } internal static void VerifySemanticDiagnostics( this EditScript<SyntaxNode> editScript, RudeEditDiagnosticDescription[] diagnostics, EditAndContinueCapabilities? capabilities) { VerifySemanticDiagnostics(editScript, activeStatements: null, targetFrameworks: null, capabilities, diagnostics); } internal static void VerifySemanticDiagnostics( this EditScript<SyntaxNode> editScript, ActiveStatementsDescription? activeStatements = null, TargetFramework[]? targetFrameworks = null, EditAndContinueCapabilities? capabilities = null, params RudeEditDiagnosticDescription[] diagnostics) { VerifySemantics( new[] { editScript }, new[] { new DocumentAnalysisResultsDescription(activeStatements: activeStatements, diagnostics: diagnostics) }, targetFrameworks, capabilities); } internal static void VerifySemantics( this EditScript<SyntaxNode> editScript, ActiveStatementsDescription activeStatements, SemanticEditDescription[] semanticEdits, EditAndContinueCapabilities? capabilities = null) { VerifySemantics( new[] { editScript }, new[] { new DocumentAnalysisResultsDescription(activeStatements, semanticEdits: semanticEdits) }, capabilities: capabilities); } internal static void VerifySemantics( this EditScript<SyntaxNode> editScript, SemanticEditDescription[] semanticEdits, EditAndContinueCapabilities capabilities) { VerifySemantics(editScript, ActiveStatementsDescription.Empty, semanticEdits, capabilities); } internal static void VerifySemantics( this EditScript<SyntaxNode> editScript, params SemanticEditDescription[] semanticEdits) { VerifySemantics(editScript, ActiveStatementsDescription.Empty, semanticEdits, capabilities: null); } internal static void VerifySemantics( EditScript<SyntaxNode>[] editScripts, DocumentAnalysisResultsDescription[] results, TargetFramework[]? targetFrameworks = null, EditAndContinueCapabilities? capabilities = null) { foreach (var targetFramework in targetFrameworks ?? new[] { TargetFramework.NetStandard20, TargetFramework.NetCoreApp }) { new CSharpEditAndContinueTestHelpers().VerifySemantics(editScripts, targetFramework, results, capabilities); } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Test/Semantic/Extensions.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.Runtime.CompilerServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax ' This is deliberately declared in the global namespace so that it will always be discoverable (regardless of Imports). Friend Module Extensions ''' <summary> ''' This method is provided as a convenience for testing the SemanticModel.GetDeclaredSymbol implementation. ''' </summary> ''' <param name="node">This parameter will be type checked, and a NotSupportedException will be thrown if the type is not currently supported by an overload of GetDeclaredSymbol.</param> <Extension()> Friend Function GetDeclaredSymbolFromSyntaxNode(model As SemanticModel, node As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As Symbol If Not ( TypeOf node Is AggregationRangeVariableSyntax OrElse TypeOf node Is AnonymousObjectCreationExpressionSyntax OrElse TypeOf node Is SimpleImportsClauseSyntax OrElse TypeOf node Is CatchStatementSyntax OrElse TypeOf node Is CollectionRangeVariableSyntax OrElse TypeOf node Is EnumBlockSyntax OrElse TypeOf node Is EnumMemberDeclarationSyntax OrElse TypeOf node Is EnumStatementSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is ExpressionRangeVariableSyntax OrElse TypeOf node Is ForEachStatementSyntax OrElse TypeOf node Is FieldInitializerSyntax OrElse TypeOf node Is ForStatementSyntax OrElse TypeOf node Is LabelStatementSyntax OrElse TypeOf node Is MethodBaseSyntax OrElse TypeOf node Is MethodBlockSyntax OrElse TypeOf node Is ModifiedIdentifierSyntax OrElse TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is NamespaceStatementSyntax OrElse TypeOf node Is ParameterSyntax OrElse TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is PropertyStatementSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is TypeParameterSyntax OrElse TypeOf node Is TypeStatementSyntax) _ Then Throw New NotSupportedException("This node type is not supported.") End If Return DirectCast(model.GetDeclaredSymbol(node, cancellationToken), Symbol) End Function End Module
' Licensed to the .NET Foundation under one or more 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.Runtime.CompilerServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax ' This is deliberately declared in the global namespace so that it will always be discoverable (regardless of Imports). Friend Module Extensions ''' <summary> ''' This method is provided as a convenience for testing the SemanticModel.GetDeclaredSymbol implementation. ''' </summary> ''' <param name="node">This parameter will be type checked, and a NotSupportedException will be thrown if the type is not currently supported by an overload of GetDeclaredSymbol.</param> <Extension()> Friend Function GetDeclaredSymbolFromSyntaxNode(model As SemanticModel, node As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As Symbol If Not ( TypeOf node Is AggregationRangeVariableSyntax OrElse TypeOf node Is AnonymousObjectCreationExpressionSyntax OrElse TypeOf node Is SimpleImportsClauseSyntax OrElse TypeOf node Is CatchStatementSyntax OrElse TypeOf node Is CollectionRangeVariableSyntax OrElse TypeOf node Is EnumBlockSyntax OrElse TypeOf node Is EnumMemberDeclarationSyntax OrElse TypeOf node Is EnumStatementSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is ExpressionRangeVariableSyntax OrElse TypeOf node Is ForEachStatementSyntax OrElse TypeOf node Is FieldInitializerSyntax OrElse TypeOf node Is ForStatementSyntax OrElse TypeOf node Is LabelStatementSyntax OrElse TypeOf node Is MethodBaseSyntax OrElse TypeOf node Is MethodBlockSyntax OrElse TypeOf node Is ModifiedIdentifierSyntax OrElse TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is NamespaceStatementSyntax OrElse TypeOf node Is ParameterSyntax OrElse TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is PropertyStatementSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is TypeParameterSyntax OrElse TypeOf node Is TypeStatementSyntax) _ Then Throw New NotSupportedException("This node type is not supported.") End If Return DirectCast(model.GetDeclaredSymbol(node, cancellationToken), Symbol) End Function End Module
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/EditorConfig/EditorConfigNamingStyleParser_NamingRule.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.NamingStyles; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal static partial class EditorConfigNamingStyleParser { private static bool TryGetSerializableNamingRule( string namingRuleTitle, SymbolSpecification symbolSpec, NamingStyle namingStyle, IReadOnlyDictionary<string, string> conventionsDictionary, [NotNullWhen(true)] out SerializableNamingRule? serializableNamingRule) { if (!TryGetRuleSeverity(namingRuleTitle, conventionsDictionary, out var severity)) { serializableNamingRule = null; return false; } serializableNamingRule = new SerializableNamingRule() { EnforcementLevel = severity, NamingStyleID = namingStyle.ID, SymbolSpecificationID = symbolSpec.ID }; return true; } internal static bool TryGetRuleSeverity( string namingRuleName, IReadOnlyDictionary<string, (string value, TextLine? line)> conventionsDictionary, out (ReportDiagnostic severity, TextLine? line) value) => TryGetRuleSeverity(namingRuleName, conventionsDictionary, x => x.value, x => x.line, out value); private static bool TryGetRuleSeverity( string namingRuleName, IReadOnlyDictionary<string, string> conventionsDictionary, out ReportDiagnostic severity) { var result = TryGetRuleSeverity<string, object?>( namingRuleName, conventionsDictionary, x => x, x => null, // we don't have a tuple out var tuple); severity = tuple.severity; return result; } private static bool TryGetRuleSeverity<T, V>( string namingRuleName, IReadOnlyDictionary<string, T> conventionsDictionary, Func<T, string> valueSelector, Func<T, V> partSelector, out (ReportDiagnostic severity, V value) value) { if (conventionsDictionary.TryGetValue($"dotnet_naming_rule.{namingRuleName}.severity", out var result)) { var severity = ParseEnforcementLevel(valueSelector(result) ?? string.Empty); value = (severity, partSelector(result)); return true; } value = default; return false; } private static ReportDiagnostic ParseEnforcementLevel(string ruleSeverity) { switch (ruleSeverity) { case EditorConfigSeverityStrings.None: return ReportDiagnostic.Suppress; case EditorConfigSeverityStrings.Refactoring: case EditorConfigSeverityStrings.Silent: return ReportDiagnostic.Hidden; case EditorConfigSeverityStrings.Suggestion: return ReportDiagnostic.Info; case EditorConfigSeverityStrings.Warning: return ReportDiagnostic.Warn; case EditorConfigSeverityStrings.Error: return ReportDiagnostic.Error; default: return ReportDiagnostic.Hidden; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.NamingStyles; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal static partial class EditorConfigNamingStyleParser { private static bool TryGetSerializableNamingRule( string namingRuleTitle, SymbolSpecification symbolSpec, NamingStyle namingStyle, IReadOnlyDictionary<string, string> conventionsDictionary, [NotNullWhen(true)] out SerializableNamingRule? serializableNamingRule) { if (!TryGetRuleSeverity(namingRuleTitle, conventionsDictionary, out var severity)) { serializableNamingRule = null; return false; } serializableNamingRule = new SerializableNamingRule() { EnforcementLevel = severity, NamingStyleID = namingStyle.ID, SymbolSpecificationID = symbolSpec.ID }; return true; } internal static bool TryGetRuleSeverity( string namingRuleName, IReadOnlyDictionary<string, (string value, TextLine? line)> conventionsDictionary, out (ReportDiagnostic severity, TextLine? line) value) => TryGetRuleSeverity(namingRuleName, conventionsDictionary, x => x.value, x => x.line, out value); private static bool TryGetRuleSeverity( string namingRuleName, IReadOnlyDictionary<string, string> conventionsDictionary, out ReportDiagnostic severity) { var result = TryGetRuleSeverity<string, object?>( namingRuleName, conventionsDictionary, x => x, x => null, // we don't have a tuple out var tuple); severity = tuple.severity; return result; } private static bool TryGetRuleSeverity<T, V>( string namingRuleName, IReadOnlyDictionary<string, T> conventionsDictionary, Func<T, string> valueSelector, Func<T, V> partSelector, out (ReportDiagnostic severity, V value) value) { if (conventionsDictionary.TryGetValue($"dotnet_naming_rule.{namingRuleName}.severity", out var result)) { var severity = ParseEnforcementLevel(valueSelector(result) ?? string.Empty); value = (severity, partSelector(result)); return true; } value = default; return false; } private static ReportDiagnostic ParseEnforcementLevel(string ruleSeverity) { switch (ruleSeverity) { case EditorConfigSeverityStrings.None: return ReportDiagnostic.Suppress; case EditorConfigSeverityStrings.Refactoring: case EditorConfigSeverityStrings.Silent: return ReportDiagnostic.Hidden; case EditorConfigSeverityStrings.Suggestion: return ReportDiagnostic.Info; case EditorConfigSeverityStrings.Warning: return ReportDiagnostic.Warn; case EditorConfigSeverityStrings.Error: return ReportDiagnostic.Error; default: return ReportDiagnostic.Hidden; } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/Compilation/SpeculativeBindingOption.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Describes the kind of binding to be performed in one of the SemanticModel /// speculative binding methods. /// </summary> public enum SpeculativeBindingOption { /// <summary> /// Binds the given expression using the normal expression binding rules /// that would occur during normal binding of expressions. /// </summary> BindAsExpression = 0, /// <summary> /// Binds the given expression as a type or namespace only. If this option /// is selected, then the given expression must derive from TypeSyntax. /// </summary> BindAsTypeOrNamespace = 1 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Describes the kind of binding to be performed in one of the SemanticModel /// speculative binding methods. /// </summary> public enum SpeculativeBindingOption { /// <summary> /// Binds the given expression using the normal expression binding rules /// that would occur during normal binding of expressions. /// </summary> BindAsExpression = 0, /// <summary> /// Binds the given expression as a type or namespace only. If this option /// is selected, then the given expression must derive from TypeSyntax. /// </summary> BindAsTypeOrNamespace = 1 } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/CommandLine/CommandLineAnalyzerReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Describes a command line analyzer assembly specification. /// </summary> [DebuggerDisplay("{FilePath,nq}")] public struct CommandLineAnalyzerReference : IEquatable<CommandLineAnalyzerReference> { private readonly string _path; public CommandLineAnalyzerReference(string path) { _path = path; } /// <summary> /// Assembly file path. /// </summary> public string FilePath { get { return _path; } } public override bool Equals(object? obj) { return obj is CommandLineAnalyzerReference && base.Equals((CommandLineAnalyzerReference)obj); } public bool Equals(CommandLineAnalyzerReference other) { return _path == other._path; } public override int GetHashCode() { return Hash.Combine(_path, 0); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Describes a command line analyzer assembly specification. /// </summary> [DebuggerDisplay("{FilePath,nq}")] public struct CommandLineAnalyzerReference : IEquatable<CommandLineAnalyzerReference> { private readonly string _path; public CommandLineAnalyzerReference(string path) { _path = path; } /// <summary> /// Assembly file path. /// </summary> public string FilePath { get { return _path; } } public override bool Equals(object? obj) { return obj is CommandLineAnalyzerReference && base.Equals((CommandLineAnalyzerReference)obj); } public bool Equals(CommandLineAnalyzerReference other) { return _path == other._path; } public override int GetHashCode() { return Hash.Combine(_path, 0); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.CSharp.EncapsulateField; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EncapsulateField { [UseExportProvider] public class EncapsulateFieldCommandHandlerTests { [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public async Task EncapsulatePrivateField() { var text = @" class C { private int f$$ield; private void goo() { field = 3; } }"; var expected = @" class C { private int field; public int Field { get { return field; } set { field = value; } } private void goo() { Field = 3; } }"; using var state = EncapsulateFieldTestState.Create(text); await state.AssertEncapsulateAsAsync(expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public async Task EncapsulateNonPrivateField() { var text = @" class C { protected int fi$$eld; private void goo() { field = 3; } }"; var expected = @" class C { private int field; protected int Field { get { return field; } set { field = value; } } private void goo() { Field = 3; } }"; using var state = EncapsulateFieldTestState.Create(text); await state.AssertEncapsulateAsAsync(expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public async Task DialogShownIfNotFieldsFound() { var text = @" class$$ C { private int field; private void goo() { field = 3; } }"; using var state = EncapsulateFieldTestState.Create(text); await state.AssertErrorAsync(); } [WorkItem(1086632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1086632")] [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public async Task EncapsulateTwoFields() { var text = @" class Program { [|static int A = 1; static int B = A;|] static void Main(string[] args) { System.Console.WriteLine(A); System.Console.WriteLine(B); } } "; var expected = @" class Program { static int A = 1; static int B = A1; public static int A1 { get { return A; } set { A = value; } } public static int B1 { get { return B; } set { B = value; } } static void Main(string[] args) { System.Console.WriteLine(A1); System.Console.WriteLine(B1); } } "; using var state = EncapsulateFieldTestState.Create(text); await state.AssertEncapsulateAsAsync(expected); } [WpfFact] [Trait(Traits.Feature, Traits.Features.EncapsulateField)] [Trait(Traits.Feature, Traits.Features.Interactive)] public void EncapsulateFieldCommandDisabledInSubmission() { using var workspace = TestWorkspace.Create(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> class C { object $$goo; } </Submission> </Workspace> "), workspaceKind: WorkspaceKind.Interactive, composition: EditorTestCompositions.EditorFeaturesWpf); // Force initialization. workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList(); var textView = workspace.Documents.Single().GetTextView(); var handler = workspace.ExportProvider.GetCommandHandler<EncapsulateFieldCommandHandler>(PredefinedCommandHandlerNames.EncapsulateField, ContentTypeNames.CSharpContentType); var state = handler.GetCommandState(new EncapsulateFieldCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.CSharp.EncapsulateField; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EncapsulateField { [UseExportProvider] public class EncapsulateFieldCommandHandlerTests { [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public async Task EncapsulatePrivateField() { var text = @" class C { private int f$$ield; private void goo() { field = 3; } }"; var expected = @" class C { private int field; public int Field { get { return field; } set { field = value; } } private void goo() { Field = 3; } }"; using var state = EncapsulateFieldTestState.Create(text); await state.AssertEncapsulateAsAsync(expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public async Task EncapsulateNonPrivateField() { var text = @" class C { protected int fi$$eld; private void goo() { field = 3; } }"; var expected = @" class C { private int field; protected int Field { get { return field; } set { field = value; } } private void goo() { Field = 3; } }"; using var state = EncapsulateFieldTestState.Create(text); await state.AssertEncapsulateAsAsync(expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public async Task DialogShownIfNotFieldsFound() { var text = @" class$$ C { private int field; private void goo() { field = 3; } }"; using var state = EncapsulateFieldTestState.Create(text); await state.AssertErrorAsync(); } [WorkItem(1086632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1086632")] [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public async Task EncapsulateTwoFields() { var text = @" class Program { [|static int A = 1; static int B = A;|] static void Main(string[] args) { System.Console.WriteLine(A); System.Console.WriteLine(B); } } "; var expected = @" class Program { static int A = 1; static int B = A1; public static int A1 { get { return A; } set { A = value; } } public static int B1 { get { return B; } set { B = value; } } static void Main(string[] args) { System.Console.WriteLine(A1); System.Console.WriteLine(B1); } } "; using var state = EncapsulateFieldTestState.Create(text); await state.AssertEncapsulateAsAsync(expected); } [WpfFact] [Trait(Traits.Feature, Traits.Features.EncapsulateField)] [Trait(Traits.Feature, Traits.Features.Interactive)] public void EncapsulateFieldCommandDisabledInSubmission() { using var workspace = TestWorkspace.Create(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> class C { object $$goo; } </Submission> </Workspace> "), workspaceKind: WorkspaceKind.Interactive, composition: EditorTestCompositions.EditorFeaturesWpf); // Force initialization. workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList(); var textView = workspace.Documents.Single().GetTextView(); var handler = workspace.ExportProvider.GetCommandHandler<EncapsulateFieldCommandHandler>(PredefinedCommandHandlerNames.EncapsulateField, ContentTypeNames.CSharpContentType); var state = handler.GetCommandState(new EncapsulateFieldCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/VisualBasicTest/Diagnostics/AddImport/AddImportTests_NuGet.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.AddImport Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Packaging Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.VisualBasic.AddImport Imports Moq Imports ProviderData = System.Tuple(Of Microsoft.CodeAnalysis.Packaging.IPackageInstallerService, Microsoft.CodeAnalysis.SymbolSearch.ISymbolSearchService) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.AddImport <Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)> Public Class AddImportNuGetTests Inherits AbstractAddImportTests Private Shared ReadOnly NuGetPackageSources As ImmutableArray(Of PackageSource) = ImmutableArray.Create(New PackageSource(PackageSourceHelper.NugetOrgSourceName, "http://nuget.org")) Protected Overrides Sub InitializeWorkspace(workspace As TestWorkspace, parameters As TestParameters) workspace.GlobalOptions.SetGlobalOption(New OptionKey(SymbolSearchOptionsStorage.SearchNuGetPackages, LanguageNames.VisualBasic), True) workspace.GlobalOptions.SetGlobalOption(New OptionKey(SymbolSearchOptionsStorage.SearchReferenceAssemblies, LanguageNames.VisualBasic), True) End Sub Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) ' This is used by inherited tests to ensure the properties of diagnostic analyzers are correct. It's not ' needed by the tests in this class, but can't throw an exception. Return (Nothing, Nothing) End Function Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, parameters As TestParameters) As (DiagnosticAnalyzer, CodeFixProvider) Dim data = DirectCast(parameters.fixProviderData, ProviderData) Return (Nothing, New VisualBasicAddImportCodeFixProvider(data.Item1, data.Item2)) End Function Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return FlattenActions(actions) End Function <Fact> Public Async Function TestSearchPackageSingleName() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackageAsync(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(SpecializedTasks.True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(PackageSourceHelper.NugetOrgSourceName, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestSearchPackageMultipleNames() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackageAsync(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(SpecializedTasks.True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(PackageSourceHelper.NugetOrgSourceName, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NS1.NS2 Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestFailedInstallDoesNotChangeFile() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackageAsync(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(SpecializedTasks.False) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(PackageSourceHelper.NugetOrgSourceName, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestMissingIfPackageAlreadyInstalled() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.IsInstalled(It.IsAny(Of Workspace)(), It.IsAny(Of ProjectId)(), "NuGetPackage")). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(PackageSourceHelper.NugetOrgSourceName, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestMissingInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", New TestParameters(fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object))) End Function <Fact> Public Async Function TestOptionsOffered() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "1.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "2.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.GetInstalledVersions("NuGetPackage")). Returns(ImmutableArray.Create("1.0", "2.0")) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(PackageSourceHelper.NugetOrgSourceName, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Dim data = New ProviderData(installerServiceMock.Object, packageServiceMock.Object) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", String.Format(FeaturesResources.Use_local_version_0, "1.0"), parameters:=New TestParameters(fixProviderData:=data)) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", String.Format(FeaturesResources.Use_local_version_0, "2.0"), parameters:=New TestParameters(index:=1, fixProviderData:=data)) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", FeaturesResources.Find_and_install_latest_version, parameters:=New TestParameters(index:=2, fixProviderData:=data)) End Function <Fact> Public Async Function TestInstallGetsCalledNoVersion() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackageAsync(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", Nothing, It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(SpecializedTasks.True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(PackageSourceHelper.NugetOrgSourceName, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) installerServiceMock.Verify() End Function <Fact> Public Async Function TestInstallGetsCalledWithVersion() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "1.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.GetInstalledVersions("NuGetPackage")). Returns(ImmutableArray.Create("1.0")) installerServiceMock.Setup(Function(s) s.TryInstallPackageAsync(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", "1.0", It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(SpecializedTasks.True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(PackageSourceHelper.NugetOrgSourceName, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) installerServiceMock.Verify() End Function Private Shared Function CreateSearchResult(packageName As String, typeName As String, nameParts As ImmutableArray(Of String)) As ValueTask(Of ImmutableArray(Of PackageWithTypeResult)) Return CreateSearchResult(New PackageWithTypeResult( packageName:=packageName, rank:=0, typeName:=typeName, version:=Nothing, containingNamespaceNames:=nameParts)) End Function Private Shared Function CreateSearchResult(ParamArray results As PackageWithTypeResult()) As ValueTask(Of ImmutableArray(Of PackageWithTypeResult)) Return ValueTaskFactory.FromResult(ImmutableArray.Create(results)) End Function Private Shared Function CreateNameParts(ParamArray parts As String()) As ImmutableArray(Of String) Return parts.ToImmutableArray() End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.AddImport Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Packaging Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.VisualBasic.AddImport Imports Moq Imports ProviderData = System.Tuple(Of Microsoft.CodeAnalysis.Packaging.IPackageInstallerService, Microsoft.CodeAnalysis.SymbolSearch.ISymbolSearchService) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.AddImport <Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)> Public Class AddImportNuGetTests Inherits AbstractAddImportTests Private Shared ReadOnly NuGetPackageSources As ImmutableArray(Of PackageSource) = ImmutableArray.Create(New PackageSource(PackageSourceHelper.NugetOrgSourceName, "http://nuget.org")) Protected Overrides Sub InitializeWorkspace(workspace As TestWorkspace, parameters As TestParameters) workspace.GlobalOptions.SetGlobalOption(New OptionKey(SymbolSearchOptionsStorage.SearchNuGetPackages, LanguageNames.VisualBasic), True) workspace.GlobalOptions.SetGlobalOption(New OptionKey(SymbolSearchOptionsStorage.SearchReferenceAssemblies, LanguageNames.VisualBasic), True) End Sub Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) ' This is used by inherited tests to ensure the properties of diagnostic analyzers are correct. It's not ' needed by the tests in this class, but can't throw an exception. Return (Nothing, Nothing) End Function Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, parameters As TestParameters) As (DiagnosticAnalyzer, CodeFixProvider) Dim data = DirectCast(parameters.fixProviderData, ProviderData) Return (Nothing, New VisualBasicAddImportCodeFixProvider(data.Item1, data.Item2)) End Function Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return FlattenActions(actions) End Function <Fact> Public Async Function TestSearchPackageSingleName() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackageAsync(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(SpecializedTasks.True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(PackageSourceHelper.NugetOrgSourceName, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestSearchPackageMultipleNames() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackageAsync(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(SpecializedTasks.True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(PackageSourceHelper.NugetOrgSourceName, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NS1.NS2 Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestFailedInstallDoesNotChangeFile() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackageAsync(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(SpecializedTasks.False) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(PackageSourceHelper.NugetOrgSourceName, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestMissingIfPackageAlreadyInstalled() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.IsInstalled(It.IsAny(Of Workspace)(), It.IsAny(Of ProjectId)(), "NuGetPackage")). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(PackageSourceHelper.NugetOrgSourceName, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestMissingInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", New TestParameters(fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object))) End Function <Fact> Public Async Function TestOptionsOffered() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "1.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "2.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.GetInstalledVersions("NuGetPackage")). Returns(ImmutableArray.Create("1.0", "2.0")) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(PackageSourceHelper.NugetOrgSourceName, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Dim data = New ProviderData(installerServiceMock.Object, packageServiceMock.Object) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", String.Format(FeaturesResources.Use_local_version_0, "1.0"), parameters:=New TestParameters(fixProviderData:=data)) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", String.Format(FeaturesResources.Use_local_version_0, "2.0"), parameters:=New TestParameters(index:=1, fixProviderData:=data)) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", FeaturesResources.Find_and_install_latest_version, parameters:=New TestParameters(index:=2, fixProviderData:=data)) End Function <Fact> Public Async Function TestInstallGetsCalledNoVersion() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackageAsync(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", Nothing, It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(SpecializedTasks.True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(PackageSourceHelper.NugetOrgSourceName, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) installerServiceMock.Verify() End Function <Fact> Public Async Function TestInstallGetsCalledWithVersion() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "1.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.GetInstalledVersions("NuGetPackage")). Returns(ImmutableArray.Create("1.0")) installerServiceMock.Setup(Function(s) s.TryInstallPackageAsync(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", "1.0", It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(SpecializedTasks.True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(PackageSourceHelper.NugetOrgSourceName, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) installerServiceMock.Verify() End Function Private Shared Function CreateSearchResult(packageName As String, typeName As String, nameParts As ImmutableArray(Of String)) As ValueTask(Of ImmutableArray(Of PackageWithTypeResult)) Return CreateSearchResult(New PackageWithTypeResult( packageName:=packageName, rank:=0, typeName:=typeName, version:=Nothing, containingNamespaceNames:=nameParts)) End Function Private Shared Function CreateSearchResult(ParamArray results As PackageWithTypeResult()) As ValueTask(Of ImmutableArray(Of PackageWithTypeResult)) Return ValueTaskFactory.FromResult(ImmutableArray.Create(results)) End Function Private Shared Function CreateNameParts(ParamArray parts As String()) As ImmutableArray(Of String) Return parts.ToImmutableArray() End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_FlowAnalysis.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class FlowAnalysisTests <Fact> Public Sub Query1() Dim compilationDef = <compilation name="QueryExpressions"> <file name="a.vb"> Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 Sub Main() Dim q As QueryAble Dim q1 As Object = From s In q Where 2 > s Dim x1, x2, x3, x4 As Object Dim qq As New QueryAble() Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'q' is used before it has been assigned a value. A null reference exception could result at runtime. Dim q1 As Object = From s In q Where 2 > s ~ BC42104: Variable 'x1' is used before it has been assigned a value. A null reference exception could result at runtime. Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s ~~ BC42104: Variable 'x2' is used before it has been assigned a value. A null reference exception could result at runtime. Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s ~~ BC42104: Variable 'x3' is used before it has been assigned a value. A null reference exception could result at runtime. Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s ~~ BC42104: Variable 'x4' is used before it has been assigned a value. A null reference exception could result at runtime. Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s ~~ </expected>) End Sub <Fact> Public Sub Query2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim y As Integer = 0 Dim q1 As Object = From s1 In q Where [|s1 > 0|] Where 10 > s1 + y Where DirectCast(Function() System.Console.WriteLine(s1) Return True End Function, Func(Of Boolean)).Invoke() End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <Fact> Public Sub Query3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim y As Integer = 0 Dim q1 As Object = From s1 In [|q|] Where s1 > 0 Where 10 > s1 + y Where DirectCast(Function() System.Console.WriteLine(s1) Return True End Function, Func(Of Boolean)).Invoke() End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <Fact> Public Sub Query7() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim y As Integer = 0 Dim q1 As Object = [|From s1 In q Where s1 > 0 Where 10 > s1 + y Where DirectCast(Function() System.Console.WriteLine(s1) Return True End Function, Func(Of Boolean)).Invoke()|] End Sub End Class ]]></file> </compilation>) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q, y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, y, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Query4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim y As Integer = 0 Dim q1 As Object = From s1 In q Where s1 > 0 Where 10 > s1 + y Where [|DirectCast(Function() Dim z As Integer = 0 y=s1 System.Console.WriteLine(s1+z) Return True End Function, Func(Of Boolean))|].Invoke() System.Console.WriteLine(y) End Sub End Class ]]></file> </compilation>) Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1, z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Query5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim y As Integer = 0 Dim q1 As Object = From s1 In q Where s1 > 0 Where 10 > [|s1 + y|] Where DirectCast(Function() Dim z As Integer = 0 y=s1 System.Console.WriteLine(s1+z) Return True End Function, Func(Of Boolean)).Invoke() System.Console.WriteLine(y) End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, y, s1, z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, y, q1, s1, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In q Select [|s1|] Where 10 > s1 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Dim flowsIn = dataFlowAnalysisResults.DataFlowsIn(0) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Same(flowsIn, dataFlowAnalysisResults.ReadInside(0)) Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Dim ss = dataFlowAnalysisResults.WrittenOutside.Where(Function(s) s.Name.Equals("s1", StringComparison.OrdinalIgnoreCase)) Assert.Equal(ss(0).Name, ss(1).Name) Assert.NotEqual(ss(0), ss(1)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = [|From s1 In q Select s1 Where 10 > s1|] End Sub End Class ]]></file> </compilation>) Assert.Equal("s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.NotSame(dataFlowAnalysisResults.VariablesDeclared(0), dataFlowAnalysisResults.VariablesDeclared(1)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q, s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In q Select s1 = [|s1|] Where 10 > s1 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.NotSame(dataFlowAnalysisResults.ReadInside(0), GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)(1)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In q Select s2 = [|s1|] Where 10 > s2 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In q Select [|s1 + 1|] Where 10 > s1 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In [|q|] Select s1 + 1 Where 10 > s1 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select7() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In [|q|] Select 1 Where 10 > s1 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select8() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In q Select s2 = [|s1|] Where 10 > s2 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select9() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In q Select s2 = [|s1|] Where 10 > s2 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub ImplicitSelect1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s As Long In [|q|] Where s > 1 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub ImplicitSelect2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s As Long In [|q|] Where s > 1 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub ImplicitSelect3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s As Long In [|q|] Where s > 1 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact()> Public Sub ImplicitSelect4() Assert.Throws(Of System.ArgumentException)( Sub() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s [|As Long|] In q Where s > 1 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) End Sub) #If False Then Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.Captured)) #End If End Sub <Fact> Public Sub ImplicitSelect5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = [|From s As Long In q Where s > 1|] End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact()> Public Sub ImplicitSelect6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s As [|Long|] In q Where s > 1 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) #If True Then Assert.False(dataFlowAnalysisResults.Succeeded) #Else Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.Captured)) #End If End Sub <Fact()> Public Sub ImplicitSelect7() Assert.Throws(Of System.ArgumentException)( Sub() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s [|As|] Long In q Where s > 1 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) End Sub) #If False Then Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.Captured)) #End If End Sub <Fact> Public Sub ImplicitSelect8() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = [|From s In q|] End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub OrderBy1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main() Dim q As New QueryAble() Dim q1 As Object = From x In q Order By [|x|], x, x Descending Order By x Descending Select y = x End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub OrderBy2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main() Dim q As New QueryAble() Dim q1 As Object = From x In q Order By x, [|x|], x Descending Order By x Descending Select y = x End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub OrderBy3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main() Dim q As New QueryAble() Dim q1 As Object = From x In q Order By x, x, [|x|] Descending Order By x Descending Select y = x End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub OrderBy4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main() Dim q As New QueryAble() Dim q1 As Object = From x In q Order By x, x, x Descending Order By [|x|] Descending Select y = x End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub OrderBy5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main() Dim q As New QueryAble() Dim q1 As Object = From x In [|q|] Order By x, x, x Descending Order By x Descending Select y = x End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub OrderBy6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main() Dim q As New QueryAble() Dim q1 As Object = [|From x In q Order By x, x, x Descending Order By x Descending Select y = x|] End Sub End Module ]]></file> </compilation>) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub OrderBy7() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main() Dim q As New QueryAble() Dim q1 As Object = From z In q Select x = [|z|] Order By x, x, x Descending Order By x Descending Select y = x End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, z, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Query6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim y As Integer = 0 Dim q1 As Object = From s1 In q Where [|s1 > y|] System.Console.WriteLine(y) End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select10() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble1 Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble1 Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble2 Return Me End Function End Class Class QueryAble2 Public Function [Select](Of T, U)(x As Func(Of T, U)) As QueryAble2 Return Me End Function End Class Module C Sub Main() Dim q As New QueryAble1() Dim q1 As Object = From s1 In q Where 10 > s2 Select s1.MaxValue, s2 = [|s1|], s3 = s1 + 1 Select s2 + s3 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, MaxValue, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Let1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("[Select] {0}", x) Return Me End Function End Class Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; Public Function [Select](Of T, S)(this As QueryAble, x As Func(Of T, S)) As QueryAble System.Console.WriteLine("[Select] {0}", x) Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s1 In q Let s2 = [|s1|], s3 = s1 + 1 Let s4 = s2 + s3 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Let2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("[Select] {0}", x) Return Me End Function End Class Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; Public Function [Select](Of T, S)(this As QueryAble, x As Func(Of T, S)) As QueryAble System.Console.WriteLine("[Select] {0}", x) Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s1 In q Let s2 = s1, s3 = [|s1 + 1|] Let s4 = s2 + s3 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Let3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("[Select] {0}", x) Return Me End Function End Class Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; Public Function [Select](Of T, S)(this As QueryAble, x As Func(Of T, S)) As QueryAble System.Console.WriteLine("[Select] {0}", x) Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s1 In q Let s2 = s1, s3 = s1 + 1 Let s4 = [|s2 + s3|] End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub From1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0) Dim q1 As Object = From s1 In qi From s2 In [|s1|], s3 In s1 From s4 In s2 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub From2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0) Dim q1 As Object = From s1 In q from s2 In s1, s3 In [|s2|] From s4 In s3 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub From3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0) Dim q1 As Object = From s1 In q from s2 In s1, s3 In s2 From s4 In [|s3|] End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub From4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0) Dim q1 As Object = From s1 In q from s2 In s1, s3 In s2 Let s4 = [|s3|], s5 = s4 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1, s2, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2, s3, s4, s5", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub From5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0) Dim q1 As Object = From s1 In q from s2 In s1, s3 In s2 Select s4 = [|s3|] End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub From6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim q As New QueryAble(Of Integer)(0) Dim q1 As Object = From s1 In q Select s1+1 From s2 In [|q|] End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Join1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Join s2 In [|qb|] Join s3 In qs On s2 Equals s3 On s1 Equals s2 Join s4 In qu On s4 Equals s1 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Join2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Join s2 In qb Join s3 In [|qs|] On s2 Equals s3 On s1 Equals s2 Join s4 In qu On s4 Equals s1 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Join3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Join s2 In qb Join s3 In qs On s2 Equals s3 On s1 Equals s2 Join s4 In [|qu|] On s4 Equals s1 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qs, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Join4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Join s2 In qb Join s3 In qs On s2 Equals s3 On s1 Equals s2 Let s4 = [|s3|], s5 = s4 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qs, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4, s5", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Join5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Join s2 In qb Join s3 In qs On s2 Equals s3 On s1 Equals s2 Select s4 = [|s3|] End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qs, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Join6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Join s2 In qb Join s3 In qs On [|s2|] Equals s3 On s1 Equals s2 Select s4 = s3 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qs, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupBy1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy {0}", item) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy ") Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = From s1 In [|qi|] Group i1=s1 By k1=s1 Into Group, Count(), c1=Count(i1) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s1, i1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupBy2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy {0}", item) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy ") Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = [|From s1 In qi Group i1=s1 By k1=s1 Into Group, Count(), c1=Count(i1)|] End Sub End Module ]]></file> </compilation>) Assert.Equal("s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi, s1, i1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupBy3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy {0}", item) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy ") Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = From s1 In qi Group i1=s1 By k1=s1 Into Group, Count(), c1=Count([|i1|]) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("i1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("i1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupBy4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy {0}", item) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy ") Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = From s1 In qi Group By k1=[|s1|] Into Group, Count(), c1=Count(s1) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupJoin1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Group Join s2 In [|qb|] Group Join s3 In qs On s2 Equals s3 Into c1 = Count() On s1 Equals s2 Into c2 = Count(s2) Group Join s4 In qu On s4 Equals s1 Into Group End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupJoin2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Group Join s2 In qb Group Join s3 In [|qs|] On s2 Equals s3 Into c1 = Count() On s1 Equals s2 Into c2 = Count(s2) Group Join s4 In qu On s4 Equals s1 Into Group End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupJoin3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Group Join s2 In qb Group Join s3 In qs On s2 Equals s3 Into c1 = Count() On s1 Equals s2 Into c2 = Count(s2) Group Join s4 In [|qu|] On s4 Equals s1 Into Group End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qs, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupJoin4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Group Join s2 In qb Group Join s3 In qs On s2 Equals s3 Into c1 = Count() On s1 Equals [|s2|] Into c2 = Count(s2) Group Join s4 In qu On s4 Equals s1 Into Group End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupJoin5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Group Join s2 In qb Group Join s3 In qs On s2 Equals s3 Into c1 = Count() On s1 Equals s2 Into c2 = Count([|s2|]) Group Join s4 In qu On s4 Equals s1 Into Group End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupJoin6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = [|From s1 In qi Group Join s2 In qb Group Join s3 In qs On s2 Equals s3 Into c1 = Count() On s1 Equals s2 Into c2 = Count(s2) Group Join s4 In qu On s4 Equals s1 Into Group|] End Sub End Module ]]></file> </compilation>) Assert.Equal("s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi, qb, qs, qu", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi, qb, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = Aggregate s1 In [|qi|] Let s2 = s1 + 1 Into Count End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = Aggregate s1 In [|qi|] Let s2 = s1 + 1 Into Count, c = Count(s2) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = Aggregate s1 In qi Let s2 = [|s1 + 1|] Into Count End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = Aggregate s1 In qi Let s2 = [|s1 + 1|] Into Count, c = Count(s2) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = Aggregate s1 In qi Let s2 = s1 + 1 Into Count([|s2|]) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = Aggregate s1 In qi Let s2 = s1 + 1 Into Count, c = Count([|s2|]) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate7() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = [|Aggregate s1 In qi Let s2 = s1 + 1 Into Count(s2)|] End Sub End Module ]]></file> </compilation>) Assert.Equal("s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate8() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = [|Aggregate s1 In qi Let s2 = s1 + 1 Into Count, c = Count(s2)|] End Sub End Module ]]></file> </compilation>) Assert.Equal("s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate9() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in [|qb|] Aggregate s1 In qi Let s2 = s1 + 1 Into Count End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate10() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in [|qb|] Aggregate s1 In qi Let s2 = s1 + 1 Into Count, c = Count(s2) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate11() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in qb Aggregate s1 In [|qi|] Let s2 = s1 + 1 Into Count End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qb, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate12() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in qb Aggregate s1 In [|qi|] Let s2 = s1 + 1 Into Count, c = Count(s2) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qb, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate13() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in qb Aggregate s1 In qi Let s2 = [|s1 + 1|] Into Count End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate14() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in qb Aggregate s1 In qi Let s2 = [|s1 + 1|] Into Count, c = Count(s2) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate15() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in qb Aggregate s1 In qi Let s2 = s1 + 1 Into Count([|s2|]) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate16() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in qb Aggregate s1 In qi Let s2 = s1 + 1 Into Count, c = Count([|s2|]) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate17() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = [|From t1 in qb Aggregate s1 In qi Let s2 = s1 + 1 Into Count(s2)|] End Sub End Module ]]></file> </compilation>) Assert.Equal("t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi, qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi, qb, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate18() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = [|From t1 in qb Aggregate s1 In qi Let s2 = s1 + 1 Into Count, c = Count(s2)|] End Sub End Module ]]></file> </compilation>) Assert.Equal("t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi, qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi, qb, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <WorkItem(543164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543164")> <Fact()> Public Sub LambdaFunctionInsideSkipClause() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Imports System.Linq Module Module1 Sub Main(arr As String()) Dim q2 = From s1 In arr Skip [|Function() s1|] End Sub End Module ]]></file> </compilation>, errors:=<errors> BC36594: Definition of method 'Skip' is not accessible in this context. Dim q2 = From s1 In arr Skip Function() s1 ~~~~ BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type. Dim q2 = From s1 In arr Skip Function() s1 ~~~~~~~~~~~~~ </errors>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("arr", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("arr, q2, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <WorkItem(543164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543164")> <Fact()> Public Sub LambdaFunctionInsideSkipClause2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Imports System.Linq Module Module1 Sub Main(arr As String()) Dim q2 = From s1 In arr Skip [|s1|] End Sub End Module ]]></file> </compilation>, errors:=<errors> BC30451: 's1' is not declared. It may be inaccessible due to its protection level. Dim q2 = From s1 In arr Skip s1 ~~ </errors>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("arr", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("arr, q2, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) 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.Linq Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class FlowAnalysisTests <Fact> Public Sub Query1() Dim compilationDef = <compilation name="QueryExpressions"> <file name="a.vb"> Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 Sub Main() Dim q As QueryAble Dim q1 As Object = From s In q Where 2 > s Dim x1, x2, x3, x4 As Object Dim qq As New QueryAble() Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'q' is used before it has been assigned a value. A null reference exception could result at runtime. Dim q1 As Object = From s In q Where 2 > s ~ BC42104: Variable 'x1' is used before it has been assigned a value. A null reference exception could result at runtime. Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s ~~ BC42104: Variable 'x2' is used before it has been assigned a value. A null reference exception could result at runtime. Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s ~~ BC42104: Variable 'x3' is used before it has been assigned a value. A null reference exception could result at runtime. Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s ~~ BC42104: Variable 'x4' is used before it has been assigned a value. A null reference exception could result at runtime. Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s ~~ </expected>) End Sub <Fact> Public Sub Query2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim y As Integer = 0 Dim q1 As Object = From s1 In q Where [|s1 > 0|] Where 10 > s1 + y Where DirectCast(Function() System.Console.WriteLine(s1) Return True End Function, Func(Of Boolean)).Invoke() End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <Fact> Public Sub Query3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim y As Integer = 0 Dim q1 As Object = From s1 In [|q|] Where s1 > 0 Where 10 > s1 + y Where DirectCast(Function() System.Console.WriteLine(s1) Return True End Function, Func(Of Boolean)).Invoke() End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <Fact> Public Sub Query7() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim y As Integer = 0 Dim q1 As Object = [|From s1 In q Where s1 > 0 Where 10 > s1 + y Where DirectCast(Function() System.Console.WriteLine(s1) Return True End Function, Func(Of Boolean)).Invoke()|] End Sub End Class ]]></file> </compilation>) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q, y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, y, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Query4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim y As Integer = 0 Dim q1 As Object = From s1 In q Where s1 > 0 Where 10 > s1 + y Where [|DirectCast(Function() Dim z As Integer = 0 y=s1 System.Console.WriteLine(s1+z) Return True End Function, Func(Of Boolean))|].Invoke() System.Console.WriteLine(y) End Sub End Class ]]></file> </compilation>) Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1, z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Query5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim y As Integer = 0 Dim q1 As Object = From s1 In q Where s1 > 0 Where 10 > [|s1 + y|] Where DirectCast(Function() Dim z As Integer = 0 y=s1 System.Console.WriteLine(s1+z) Return True End Function, Func(Of Boolean)).Invoke() System.Console.WriteLine(y) End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, y, s1, z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, y, q1, s1, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In q Select [|s1|] Where 10 > s1 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Dim flowsIn = dataFlowAnalysisResults.DataFlowsIn(0) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Same(flowsIn, dataFlowAnalysisResults.ReadInside(0)) Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Dim ss = dataFlowAnalysisResults.WrittenOutside.Where(Function(s) s.Name.Equals("s1", StringComparison.OrdinalIgnoreCase)) Assert.Equal(ss(0).Name, ss(1).Name) Assert.NotEqual(ss(0), ss(1)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = [|From s1 In q Select s1 Where 10 > s1|] End Sub End Class ]]></file> </compilation>) Assert.Equal("s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.NotSame(dataFlowAnalysisResults.VariablesDeclared(0), dataFlowAnalysisResults.VariablesDeclared(1)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q, s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In q Select s1 = [|s1|] Where 10 > s1 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.NotSame(dataFlowAnalysisResults.ReadInside(0), GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)(1)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In q Select s2 = [|s1|] Where 10 > s2 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In q Select [|s1 + 1|] Where 10 > s1 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In [|q|] Select s1 + 1 Where 10 > s1 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select7() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In [|q|] Select 1 Where 10 > s1 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select8() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In q Select s2 = [|s1|] Where 10 > s2 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select9() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s1 In q Select s2 = [|s1|] Where 10 > s2 End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub ImplicitSelect1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s As Long In [|q|] Where s > 1 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub ImplicitSelect2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s As Long In [|q|] Where s > 1 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub ImplicitSelect3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s As Long In [|q|] Where s > 1 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact()> Public Sub ImplicitSelect4() Assert.Throws(Of System.ArgumentException)( Sub() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s [|As Long|] In q Where s > 1 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) End Sub) #If False Then Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.Captured)) #End If End Sub <Fact> Public Sub ImplicitSelect5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = [|From s As Long In q Where s > 1|] End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact()> Public Sub ImplicitSelect6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s As [|Long|] In q Where s > 1 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) #If True Then Assert.False(dataFlowAnalysisResults.Succeeded) #Else Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.Captured)) #End If End Sub <Fact()> Public Sub ImplicitSelect7() Assert.Throws(Of System.ArgumentException)( Sub() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s [|As|] Long In q Where s > 1 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) End Sub) #If False Then Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.Captured)) #End If End Sub <Fact> Public Sub ImplicitSelect8() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = [|From s In q|] End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub OrderBy1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main() Dim q As New QueryAble() Dim q1 As Object = From x In q Order By [|x|], x, x Descending Order By x Descending Select y = x End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub OrderBy2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main() Dim q As New QueryAble() Dim q1 As Object = From x In q Order By x, [|x|], x Descending Order By x Descending Select y = x End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub OrderBy3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main() Dim q As New QueryAble() Dim q1 As Object = From x In q Order By x, x, [|x|] Descending Order By x Descending Select y = x End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub OrderBy4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main() Dim q As New QueryAble() Dim q1 As Object = From x In q Order By x, x, x Descending Order By [|x|] Descending Select y = x End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub OrderBy5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main() Dim q As New QueryAble() Dim q1 As Object = From x In [|q|] Order By x, x, x Descending Order By x Descending Select y = x End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub OrderBy6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main() Dim q As New QueryAble() Dim q1 As Object = [|From x In q Order By x, x, x Descending Order By x Descending Select y = x|] End Sub End Module ]]></file> </compilation>) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub OrderBy7() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main() Dim q As New QueryAble() Dim q1 As Object = From z In q Select x = [|z|] Order By x, x, x Descending Order By x Descending Select y = x End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, z, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Query6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Class C Sub Main(args As String()) Dim q As New QueryAble() Dim y As Integer = 0 Dim q1 As Object = From s1 In q Where [|s1 > y|] System.Console.WriteLine(y) End Sub End Class ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Select10() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Class QueryAble1 Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble1 Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble2 Return Me End Function End Class Class QueryAble2 Public Function [Select](Of T, U)(x As Func(Of T, U)) As QueryAble2 Return Me End Function End Class Module C Sub Main() Dim q As New QueryAble1() Dim q1 As Object = From s1 In q Where 10 > s2 Select s1.MaxValue, s2 = [|s1|], s3 = s1 + 1 Select s2 + s3 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, MaxValue, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Let1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("[Select] {0}", x) Return Me End Function End Class Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; Public Function [Select](Of T, S)(this As QueryAble, x As Func(Of T, S)) As QueryAble System.Console.WriteLine("[Select] {0}", x) Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s1 In q Let s2 = [|s1|], s3 = s1 + 1 Let s4 = s2 + s3 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Let2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("[Select] {0}", x) Return Me End Function End Class Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; Public Function [Select](Of T, S)(this As QueryAble, x As Func(Of T, S)) As QueryAble System.Console.WriteLine("[Select] {0}", x) Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s1 In q Let s2 = s1, s3 = [|s1 + 1|] Let s4 = s2 + s3 End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Let3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("[Select] {0}", x) Return Me End Function End Class Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; Public Function [Select](Of T, S)(this As QueryAble, x As Func(Of T, S)) As QueryAble System.Console.WriteLine("[Select] {0}", x) Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s1 In q Let s2 = s1, s3 = s1 + 1 Let s4 = [|s2 + s3|] End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub From1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0) Dim q1 As Object = From s1 In qi From s2 In [|s1|], s3 In s1 From s4 In s2 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub From2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0) Dim q1 As Object = From s1 In q from s2 In s1, s3 In [|s2|] From s4 In s3 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub From3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0) Dim q1 As Object = From s1 In q from s2 In s1, s3 In s2 From s4 In [|s3|] End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub From4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0) Dim q1 As Object = From s1 In q from s2 In s1, s3 In s2 Let s4 = [|s3|], s5 = s4 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1, s2, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2, s3, s4, s5", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub From5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0) Dim q1 As Object = From s1 In q from s2 In s1, s3 In s2 Select s4 = [|s3|] End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub From6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim q As New QueryAble(Of Integer)(0) Dim q1 As Object = From s1 In q Select s1+1 From s2 In [|q|] End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Join1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Join s2 In [|qb|] Join s3 In qs On s2 Equals s3 On s1 Equals s2 Join s4 In qu On s4 Equals s1 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Join2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Join s2 In qb Join s3 In [|qs|] On s2 Equals s3 On s1 Equals s2 Join s4 In qu On s4 Equals s1 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Join3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Join s2 In qb Join s3 In qs On s2 Equals s3 On s1 Equals s2 Join s4 In [|qu|] On s4 Equals s1 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qs, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Join4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Join s2 In qb Join s3 In qs On s2 Equals s3 On s1 Equals s2 Let s4 = [|s3|], s5 = s4 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qs, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4, s5", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Join5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Join s2 In qb Join s3 In qs On s2 Equals s3 On s1 Equals s2 Select s4 = [|s3|] End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qs, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Join6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Join s2 In qb Join s3 In qs On [|s2|] Equals s3 On s1 Equals s2 Select s4 = s3 End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qs, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupBy1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy {0}", item) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy ") Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = From s1 In [|qi|] Group i1=s1 By k1=s1 Into Group, Count(), c1=Count(i1) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s1, i1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupBy2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy {0}", item) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy ") Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = [|From s1 In qi Group i1=s1 By k1=s1 Into Group, Count(), c1=Count(i1)|] End Sub End Module ]]></file> </compilation>) Assert.Equal("s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi, s1, i1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupBy3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy {0}", item) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy ") Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = From s1 In qi Group i1=s1 By k1=s1 Into Group, Count(), c1=Count([|i1|]) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("i1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("i1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupBy4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy {0}", item) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy ") Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = From s1 In qi Group By k1=[|s1|] Into Group, Count(), c1=Count(s1) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupJoin1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Group Join s2 In [|qb|] Group Join s3 In qs On s2 Equals s3 Into c1 = Count() On s1 Equals s2 Into c2 = Count(s2) Group Join s4 In qu On s4 Equals s1 Into Group End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupJoin2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Group Join s2 In qb Group Join s3 In [|qs|] On s2 Equals s3 Into c1 = Count() On s1 Equals s2 Into c2 = Count(s2) Group Join s4 In qu On s4 Equals s1 Into Group End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupJoin3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Group Join s2 In qb Group Join s3 In qs On s2 Equals s3 Into c1 = Count() On s1 Equals s2 Into c2 = Count(s2) Group Join s4 In [|qu|] On s4 Equals s1 Into Group End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qs, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupJoin4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Group Join s2 In qb Group Join s3 In qs On s2 Equals s3 Into c1 = Count() On s1 Equals [|s2|] Into c2 = Count(s2) Group Join s4 In qu On s4 Equals s1 Into Group End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupJoin5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s1 In qi Group Join s2 In qb Group Join s3 In qs On s2 Equals s3 Into c1 = Count() On s1 Equals s2 Into c2 = Count([|s2|]) Group Join s4 In qu On s4 Equals s1 Into Group End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub GroupJoin6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = [|From s1 In qi Group Join s2 In qb Group Join s3 In qs On s2 Equals s3 Into c1 = Count() On s1 Equals s2 Into c2 = Count(s2) Group Join s4 In qu On s4 Equals s1 Into Group|] End Sub End Module ]]></file> </compilation>) Assert.Equal("s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi, qb, qs, qu", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi, qb, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, qs, qu, ql, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = Aggregate s1 In [|qi|] Let s2 = s1 + 1 Into Count End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = Aggregate s1 In [|qi|] Let s2 = s1 + 1 Into Count, c = Count(s2) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = Aggregate s1 In qi Let s2 = [|s1 + 1|] Into Count End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = Aggregate s1 In qi Let s2 = [|s1 + 1|] Into Count, c = Count(s2) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = Aggregate s1 In qi Let s2 = s1 + 1 Into Count([|s2|]) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = Aggregate s1 In qi Let s2 = s1 + 1 Into Count, c = Count([|s2|]) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate7() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = [|Aggregate s1 In qi Let s2 = s1 + 1 Into Count(s2)|] End Sub End Module ]]></file> </compilation>) Assert.Equal("s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate8() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = [|Aggregate s1 In qi Let s2 = s1 + 1 Into Count, c = Count(s2)|] End Sub End Module ]]></file> </compilation>) Assert.Equal("s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate9() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in [|qb|] Aggregate s1 In qi Let s2 = s1 + 1 Into Count End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate10() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in [|qb|] Aggregate s1 In qi Let s2 = s1 + 1 Into Count, c = Count(s2) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate11() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in qb Aggregate s1 In [|qi|] Let s2 = s1 + 1 Into Count End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qb, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate12() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in qb Aggregate s1 In [|qi|] Let s2 = s1 + 1 Into Count, c = Count(s2) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qb, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate13() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in qb Aggregate s1 In qi Let s2 = [|s1 + 1|] Into Count End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate14() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in qb Aggregate s1 In qi Let s2 = [|s1 + 1|] Into Count, c = Count(s2) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate15() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in qb Aggregate s1 In qi Let s2 = s1 + 1 Into Count([|s2|]) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate16() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = From t1 in qb Aggregate s1 In qi Let s2 = s1 + 1 Into Count, c = Count([|s2|]) End Sub End Module ]]></file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("qi, qb, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate17() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = [|From t1 in qb Aggregate s1 In qi Let s2 = s1 + 1 Into Count(s2)|] End Sub End Module ]]></file> </compilation>) Assert.Equal("t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi, qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi, qb, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <Fact> Public Sub Aggregate18() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim q1 As Object = [|From t1 in qb Aggregate s1 In qi Let s2 = s1 + 1 Into Count, c = Count(s2)|] End Sub End Module ]]></file> </compilation>) Assert.Equal("t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("qi, qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("qi, qb, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("qi, qb, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <WorkItem(543164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543164")> <Fact()> Public Sub LambdaFunctionInsideSkipClause() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Imports System.Linq Module Module1 Sub Main(arr As String()) Dim q2 = From s1 In arr Skip [|Function() s1|] End Sub End Module ]]></file> </compilation>, errors:=<errors> BC36594: Definition of method 'Skip' is not accessible in this context. Dim q2 = From s1 In arr Skip Function() s1 ~~~~ BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type. Dim q2 = From s1 In arr Skip Function() s1 ~~~~~~~~~~~~~ </errors>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("arr", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("arr, q2, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <WorkItem(543164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543164")> <Fact()> Public Sub LambdaFunctionInsideSkipClause2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Imports System Imports System.Linq Module Module1 Sub Main(arr As String()) Dim q2 = From s1 In arr Skip [|s1|] End Sub End Module ]]></file> </compilation>, errors:=<errors> BC30451: 's1' is not declared. It may be inaccessible due to its protection level. Dim q2 = From s1 In arr Skip s1 ~~ </errors>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("arr", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("arr, q2, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Analyzers/Core/Analyzers/UseThrowExpression/AbstractUseThrowExpressionDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseThrowExpression { /// <summary> /// Looks for patterns of the form: /// <code> /// if (a == null) { /// throw SomeException(); /// } /// /// x = a; /// </code> /// /// and offers to change it to /// /// <code> /// x = a ?? throw SomeException(); /// </code> /// /// Note: this analyzer can be updated to run on VB once VB supports 'throw' /// expressions as well. /// </summary> internal abstract class AbstractUseThrowExpressionDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { protected AbstractUseThrowExpressionDiagnosticAnalyzer(Option2<CodeStyleOption2<bool>> preferThrowExpressionOption, string language) : base(IDEDiagnosticIds.UseThrowExpressionDiagnosticId, EnforceOnBuildValues.UseThrowExpression, preferThrowExpressionOption, language, new LocalizableResourceString(nameof(AnalyzersResources.Use_throw_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Null_check_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } protected abstract CodeStyleOption2<bool> PreferThrowExpressionStyle(OperationAnalysisContext context); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected abstract bool IsSupported(Compilation compilation); protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(startContext => { if (!IsSupported(startContext.Compilation)) { return; } var expressionTypeOpt = startContext.Compilation.ExpressionOfTType(); startContext.RegisterOperationAction(operationContext => AnalyzeOperation(operationContext, expressionTypeOpt), OperationKind.Throw); }); } private void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol? expressionTypeOpt) { var cancellationToken = context.CancellationToken; var throwOperation = (IThrowOperation)context.Operation; if (throwOperation.Exception == null) return; var throwStatementSyntax = throwOperation.Syntax; var semanticModel = context.Operation.SemanticModel; Contract.ThrowIfNull(semanticModel); var ifOperation = GetContainingIfOperation( semanticModel, throwOperation, cancellationToken); // This throw statement isn't parented by an if-statement. Nothing to // do here. if (ifOperation == null) return; if (ifOperation.WhenFalse != null) { // Can't offer this if the 'if-statement' has an 'else-clause'. return; } var option = PreferThrowExpressionStyle(context); if (!option.Value) return; if (IsInExpressionTree(semanticModel, throwStatementSyntax, expressionTypeOpt, cancellationToken)) return; if (ifOperation.Parent is not IBlockOperation containingBlock) return; if (!TryDecomposeIfCondition(ifOperation, out var localOrParameter)) return; if (!TryFindAssignmentExpression(containingBlock, ifOperation, localOrParameter, out var expressionStatement, out var assignmentExpression)) { return; } if (!localOrParameter.GetSymbolType().CanAddNullCheck()) return; // We found an assignment using this local/parameter. Now, just make sure there // were no intervening accesses between the check and the assignment. if (ValueIsAccessed( semanticModel, ifOperation, containingBlock, localOrParameter, expressionStatement, assignmentExpression)) { return; } // Ok, there were no intervening writes or accesses. This check+assignment can be simplified. var allLocations = ImmutableArray.Create( ifOperation.Syntax.GetLocation(), throwOperation.Exception.Syntax.GetLocation(), assignmentExpression.Value.Syntax.GetLocation()); context.ReportDiagnostic( DiagnosticHelper.Create(Descriptor, throwStatementSyntax.GetLocation(), option.Notification.Severity, additionalLocations: allLocations, properties: null)); } private static bool ValueIsAccessed(SemanticModel semanticModel, IConditionalOperation ifOperation, IBlockOperation containingBlock, ISymbol localOrParameter, IExpressionStatementOperation expressionStatement, IAssignmentOperation assignmentExpression) { var statements = containingBlock.Operations; var ifOperationIndex = statements.IndexOf(ifOperation); var expressionStatementIndex = statements.IndexOf(expressionStatement); if (expressionStatementIndex > ifOperationIndex + 1) { // There are intermediary statements between the check and the assignment. // Make sure they don't try to access the local. var dataFlow = semanticModel.AnalyzeDataFlow( statements[ifOperationIndex + 1].Syntax, statements[expressionStatementIndex - 1].Syntax); if (dataFlow.ReadInside.Contains(localOrParameter) || dataFlow.WrittenInside.Contains(localOrParameter)) { return true; } } // Also, have to make sure there is no read/write of the local/parameter on the left // of the assignment. For example: map[val.Id] = val; var exprDataFlow = semanticModel.AnalyzeDataFlow(assignmentExpression.Target.Syntax); return exprDataFlow.ReadInside.Contains(localOrParameter) || exprDataFlow.WrittenInside.Contains(localOrParameter); } protected abstract bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol? expressionTypeOpt, CancellationToken cancellationToken); private bool TryFindAssignmentExpression( IBlockOperation containingBlock, IConditionalOperation ifOperation, ISymbol localOrParameter, [NotNullWhen(true)] out IExpressionStatementOperation? expressionStatement, [NotNullWhen(true)] out IAssignmentOperation? assignmentExpression) { var ifOperationIndex = containingBlock.Operations.IndexOf(ifOperation); // walk forward until we find an assignment of this local/parameter into // something else. for (var i = ifOperationIndex + 1; i < containingBlock.Operations.Length; i++) { expressionStatement = containingBlock.Operations[i] as IExpressionStatementOperation; if (expressionStatement == null) { continue; } assignmentExpression = expressionStatement.Operation as IAssignmentOperation; if (assignmentExpression == null) { continue; } if (!TryGetLocalOrParameterSymbol(assignmentExpression.Value, out var assignmentValue)) { continue; } if (!Equals(localOrParameter, assignmentValue)) { continue; } return true; } expressionStatement = null; assignmentExpression = null; return false; } private bool TryDecomposeIfCondition( IConditionalOperation ifStatement, [NotNullWhen(true)] out ISymbol? localOrParameter) { localOrParameter = null; var condition = ifStatement.Condition; if (condition is not IBinaryOperation binaryOperator) { return false; } if (binaryOperator.OperatorKind != BinaryOperatorKind.Equals) { return false; } if (IsNull(binaryOperator.LeftOperand)) { return TryGetLocalOrParameterSymbol( binaryOperator.RightOperand, out localOrParameter); } if (IsNull(binaryOperator.RightOperand)) { return TryGetLocalOrParameterSymbol( binaryOperator.LeftOperand, out localOrParameter); } return false; } private bool TryGetLocalOrParameterSymbol( IOperation operation, [NotNullWhen(true)] out ISymbol? localOrParameter) { if (operation is IConversionOperation conversion && conversion.IsImplicit) { return TryGetLocalOrParameterSymbol(conversion.Operand, out localOrParameter); } else if (operation is ILocalReferenceOperation localReference) { localOrParameter = localReference.Local; return true; } else if (operation is IParameterReferenceOperation parameterReference) { localOrParameter = parameterReference.Parameter; return true; } localOrParameter = null; return false; } private static bool IsNull(IOperation operation) { return operation.ConstantValue.HasValue && operation.ConstantValue.Value == null; } private static IConditionalOperation? GetContainingIfOperation( SemanticModel semanticModel, IThrowOperation throwOperation, CancellationToken cancellationToken) { var throwStatement = throwOperation.Syntax; var containingOperation = semanticModel.GetOperation(throwStatement.GetRequiredParent(), cancellationToken); if (containingOperation is IBlockOperation block) { if (block.Operations.Length != 1) { // If we are in a block, then the block must only contain // the throw statement. return null; } // C# may have an intermediary block between the throw-statement // and the if-statement. Walk up one operation higher in that case. containingOperation = semanticModel.GetOperation(throwStatement.GetRequiredParent().GetRequiredParent(), cancellationToken); } if (containingOperation is IConditionalOperation conditionalOperation) { return conditionalOperation; } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseThrowExpression { /// <summary> /// Looks for patterns of the form: /// <code> /// if (a == null) { /// throw SomeException(); /// } /// /// x = a; /// </code> /// /// and offers to change it to /// /// <code> /// x = a ?? throw SomeException(); /// </code> /// /// Note: this analyzer can be updated to run on VB once VB supports 'throw' /// expressions as well. /// </summary> internal abstract class AbstractUseThrowExpressionDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { protected AbstractUseThrowExpressionDiagnosticAnalyzer(Option2<CodeStyleOption2<bool>> preferThrowExpressionOption, string language) : base(IDEDiagnosticIds.UseThrowExpressionDiagnosticId, EnforceOnBuildValues.UseThrowExpression, preferThrowExpressionOption, language, new LocalizableResourceString(nameof(AnalyzersResources.Use_throw_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Null_check_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } protected abstract CodeStyleOption2<bool> PreferThrowExpressionStyle(OperationAnalysisContext context); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected abstract bool IsSupported(Compilation compilation); protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(startContext => { if (!IsSupported(startContext.Compilation)) { return; } var expressionTypeOpt = startContext.Compilation.ExpressionOfTType(); startContext.RegisterOperationAction(operationContext => AnalyzeOperation(operationContext, expressionTypeOpt), OperationKind.Throw); }); } private void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol? expressionTypeOpt) { var cancellationToken = context.CancellationToken; var throwOperation = (IThrowOperation)context.Operation; if (throwOperation.Exception == null) return; var throwStatementSyntax = throwOperation.Syntax; var semanticModel = context.Operation.SemanticModel; Contract.ThrowIfNull(semanticModel); var ifOperation = GetContainingIfOperation( semanticModel, throwOperation, cancellationToken); // This throw statement isn't parented by an if-statement. Nothing to // do here. if (ifOperation == null) return; if (ifOperation.WhenFalse != null) { // Can't offer this if the 'if-statement' has an 'else-clause'. return; } var option = PreferThrowExpressionStyle(context); if (!option.Value) return; if (IsInExpressionTree(semanticModel, throwStatementSyntax, expressionTypeOpt, cancellationToken)) return; if (ifOperation.Parent is not IBlockOperation containingBlock) return; if (!TryDecomposeIfCondition(ifOperation, out var localOrParameter)) return; if (!TryFindAssignmentExpression(containingBlock, ifOperation, localOrParameter, out var expressionStatement, out var assignmentExpression)) { return; } if (!localOrParameter.GetSymbolType().CanAddNullCheck()) return; // We found an assignment using this local/parameter. Now, just make sure there // were no intervening accesses between the check and the assignment. if (ValueIsAccessed( semanticModel, ifOperation, containingBlock, localOrParameter, expressionStatement, assignmentExpression)) { return; } // Ok, there were no intervening writes or accesses. This check+assignment can be simplified. var allLocations = ImmutableArray.Create( ifOperation.Syntax.GetLocation(), throwOperation.Exception.Syntax.GetLocation(), assignmentExpression.Value.Syntax.GetLocation()); context.ReportDiagnostic( DiagnosticHelper.Create(Descriptor, throwStatementSyntax.GetLocation(), option.Notification.Severity, additionalLocations: allLocations, properties: null)); } private static bool ValueIsAccessed(SemanticModel semanticModel, IConditionalOperation ifOperation, IBlockOperation containingBlock, ISymbol localOrParameter, IExpressionStatementOperation expressionStatement, IAssignmentOperation assignmentExpression) { var statements = containingBlock.Operations; var ifOperationIndex = statements.IndexOf(ifOperation); var expressionStatementIndex = statements.IndexOf(expressionStatement); if (expressionStatementIndex > ifOperationIndex + 1) { // There are intermediary statements between the check and the assignment. // Make sure they don't try to access the local. var dataFlow = semanticModel.AnalyzeDataFlow( statements[ifOperationIndex + 1].Syntax, statements[expressionStatementIndex - 1].Syntax); if (dataFlow.ReadInside.Contains(localOrParameter) || dataFlow.WrittenInside.Contains(localOrParameter)) { return true; } } // Also, have to make sure there is no read/write of the local/parameter on the left // of the assignment. For example: map[val.Id] = val; var exprDataFlow = semanticModel.AnalyzeDataFlow(assignmentExpression.Target.Syntax); return exprDataFlow.ReadInside.Contains(localOrParameter) || exprDataFlow.WrittenInside.Contains(localOrParameter); } protected abstract bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol? expressionTypeOpt, CancellationToken cancellationToken); private bool TryFindAssignmentExpression( IBlockOperation containingBlock, IConditionalOperation ifOperation, ISymbol localOrParameter, [NotNullWhen(true)] out IExpressionStatementOperation? expressionStatement, [NotNullWhen(true)] out IAssignmentOperation? assignmentExpression) { var ifOperationIndex = containingBlock.Operations.IndexOf(ifOperation); // walk forward until we find an assignment of this local/parameter into // something else. for (var i = ifOperationIndex + 1; i < containingBlock.Operations.Length; i++) { expressionStatement = containingBlock.Operations[i] as IExpressionStatementOperation; if (expressionStatement == null) { continue; } assignmentExpression = expressionStatement.Operation as IAssignmentOperation; if (assignmentExpression == null) { continue; } if (!TryGetLocalOrParameterSymbol(assignmentExpression.Value, out var assignmentValue)) { continue; } if (!Equals(localOrParameter, assignmentValue)) { continue; } return true; } expressionStatement = null; assignmentExpression = null; return false; } private bool TryDecomposeIfCondition( IConditionalOperation ifStatement, [NotNullWhen(true)] out ISymbol? localOrParameter) { localOrParameter = null; var condition = ifStatement.Condition; if (condition is not IBinaryOperation binaryOperator) { return false; } if (binaryOperator.OperatorKind != BinaryOperatorKind.Equals) { return false; } if (IsNull(binaryOperator.LeftOperand)) { return TryGetLocalOrParameterSymbol( binaryOperator.RightOperand, out localOrParameter); } if (IsNull(binaryOperator.RightOperand)) { return TryGetLocalOrParameterSymbol( binaryOperator.LeftOperand, out localOrParameter); } return false; } private bool TryGetLocalOrParameterSymbol( IOperation operation, [NotNullWhen(true)] out ISymbol? localOrParameter) { if (operation is IConversionOperation conversion && conversion.IsImplicit) { return TryGetLocalOrParameterSymbol(conversion.Operand, out localOrParameter); } else if (operation is ILocalReferenceOperation localReference) { localOrParameter = localReference.Local; return true; } else if (operation is IParameterReferenceOperation parameterReference) { localOrParameter = parameterReference.Parameter; return true; } localOrParameter = null; return false; } private static bool IsNull(IOperation operation) { return operation.ConstantValue.HasValue && operation.ConstantValue.Value == null; } private static IConditionalOperation? GetContainingIfOperation( SemanticModel semanticModel, IThrowOperation throwOperation, CancellationToken cancellationToken) { var throwStatement = throwOperation.Syntax; var containingOperation = semanticModel.GetOperation(throwStatement.GetRequiredParent(), cancellationToken); if (containingOperation is IBlockOperation block) { if (block.Operations.Length != 1) { // If we are in a block, then the block must only contain // the throw statement. return null; } // C# may have an intermediary block between the throw-statement // and the if-statement. Walk up one operation higher in that case. containingOperation = semanticModel.GetOperation(throwStatement.GetRequiredParent().GetRequiredParent(), cancellationToken); } if (containingOperation is IConditionalOperation conditionalOperation) { return conditionalOperation; } return null; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/Test/Tagging/AsynchronousTaggerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.Structure; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Tagging { [UseExportProvider] public class AsynchronousTaggerTests : TestBase { /// <summary> /// This hits a special codepath in the product that is optimized for more than 100 spans. /// I'm leaving this test here because it covers that code path (as shown by code coverage) /// </summary> [WpfFact] [WorkItem(530368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530368")] public async Task LargeNumberOfSpans() { using var workspace = TestWorkspace.CreateCSharp(@"class Program { void M() { int z = 0; z = z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z; } }"); static List<ITagSpan<TestTag>> tagProducer(SnapshotSpan span, CancellationToken cancellationToken) { return new List<ITagSpan<TestTag>>() { new TagSpan<TestTag>(span, new TestTag()) }; } var asyncListener = new AsynchronousOperationListener(); WpfTestRunner.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(LargeNumberOfSpans)} creates asynchronous taggers"); var eventSource = CreateEventSource(); var taggerProvider = new TestTaggerProvider( workspace.GetService<IThreadingContext>(), tagProducer, eventSource, workspace.GetService<IGlobalOptionService>(), asyncListener); var document = workspace.Documents.First(); var textBuffer = document.GetTextBuffer(); var snapshot = textBuffer.CurrentSnapshot; var tagger = taggerProvider.CreateTagger<TestTag>(textBuffer); Contract.ThrowIfNull(tagger); using var disposable = (IDisposable)tagger; var spans = Enumerable.Range(0, 101).Select(i => new Span(i * 4, 1)); var snapshotSpans = new NormalizedSnapshotSpanCollection(snapshot, spans); eventSource.SendUpdateEvent(); await asyncListener.ExpeditedWaitAsync(); var tags = tagger.GetTags(snapshotSpans); Assert.Equal(1, tags.Count()); } [WpfFact] public void TestNotSynchronousOutlining() { using var workspace = TestWorkspace.CreateCSharp("class Program {\r\n\r\n}", composition: EditorTestCompositions.EditorFeaturesWpf); WpfTestRunner.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(TestNotSynchronousOutlining)} creates asynchronous taggers"); var tagProvider = workspace.ExportProvider.GetExportedValue<AbstractStructureTaggerProvider>(); var document = workspace.Documents.First(); var textBuffer = document.GetTextBuffer(); var tagger = tagProvider.CreateTagger<IStructureTag>(textBuffer); Contract.ThrowIfNull(tagger); using var disposable = (IDisposable)tagger; // The very first all to get tags will not be synchronous as this contains no #region tag var tags = tagger.GetTags(new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot.GetFullSpan())); Assert.Equal(0, tags.Count()); } [WpfFact] public void TestSynchronousOutlining() { using var workspace = TestWorkspace.CreateCSharp(@" #region x class Program { } #endregion", composition: EditorTestCompositions.EditorFeaturesWpf); WpfTestRunner.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(TestSynchronousOutlining)} creates asynchronous taggers"); var tagProvider = workspace.ExportProvider.GetExportedValue<AbstractStructureTaggerProvider>(); var document = workspace.Documents.First(); var textBuffer = document.GetTextBuffer(); var tagger = tagProvider.CreateTagger<IStructureTag>(textBuffer); Contract.ThrowIfNull(tagger); using var disposable = (IDisposable)tagger; // The very first all to get tags will be synchronous because of the #region var tags = tagger.GetTags(new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot.GetFullSpan())); Assert.Equal(2, tags.Count()); } private static TestTaggerEventSource CreateEventSource() => new TestTaggerEventSource(); private sealed class TestTag : TextMarkerTag { public TestTag() : base("Test") { } } private delegate List<ITagSpan<TestTag>> Callback(SnapshotSpan span, CancellationToken cancellationToken); private sealed class TestTaggerProvider : AsynchronousTaggerProvider<TestTag> { private readonly Callback _callback; private readonly ITaggerEventSource _eventSource; public TestTaggerProvider( IThreadingContext threadingContext, Callback callback, ITaggerEventSource eventSource, IGlobalOptionService globalOptions, IAsynchronousOperationListener asyncListener) : base(threadingContext, globalOptions, visibilityTracker: null, asyncListener) { _callback = callback; _eventSource = eventSource; } protected override TaggerDelay EventChangeDelay => TaggerDelay.NearImmediate; protected override ITaggerEventSource CreateEventSource(ITextView? textView, ITextBuffer subjectBuffer) => _eventSource; protected override Task ProduceTagsAsync( TaggerContext<TestTag> context, DocumentSnapshotSpan snapshotSpan, int? caretPosition, CancellationToken cancellationToken) { var tags = _callback(snapshotSpan.SnapshotSpan, cancellationToken); if (tags != null) { foreach (var tag in tags) { context.AddTag(tag); } } return Task.CompletedTask; } } private sealed class TestTaggerEventSource : AbstractTaggerEventSource { public TestTaggerEventSource() { } public void SendUpdateEvent() => this.RaiseChanged(); public override void Connect() { } public override void Disconnect() { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.Structure; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Tagging { [UseExportProvider] public class AsynchronousTaggerTests : TestBase { /// <summary> /// This hits a special codepath in the product that is optimized for more than 100 spans. /// I'm leaving this test here because it covers that code path (as shown by code coverage) /// </summary> [WpfFact] [WorkItem(530368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530368")] public async Task LargeNumberOfSpans() { using var workspace = TestWorkspace.CreateCSharp(@"class Program { void M() { int z = 0; z = z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z; } }"); static List<ITagSpan<TestTag>> tagProducer(SnapshotSpan span, CancellationToken cancellationToken) { return new List<ITagSpan<TestTag>>() { new TagSpan<TestTag>(span, new TestTag()) }; } var asyncListener = new AsynchronousOperationListener(); WpfTestRunner.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(LargeNumberOfSpans)} creates asynchronous taggers"); var eventSource = CreateEventSource(); var taggerProvider = new TestTaggerProvider( workspace.GetService<IThreadingContext>(), tagProducer, eventSource, workspace.GetService<IGlobalOptionService>(), asyncListener); var document = workspace.Documents.First(); var textBuffer = document.GetTextBuffer(); var snapshot = textBuffer.CurrentSnapshot; var tagger = taggerProvider.CreateTagger<TestTag>(textBuffer); Contract.ThrowIfNull(tagger); using var disposable = (IDisposable)tagger; var spans = Enumerable.Range(0, 101).Select(i => new Span(i * 4, 1)); var snapshotSpans = new NormalizedSnapshotSpanCollection(snapshot, spans); eventSource.SendUpdateEvent(); await asyncListener.ExpeditedWaitAsync(); var tags = tagger.GetTags(snapshotSpans); Assert.Equal(1, tags.Count()); } [WpfFact] public void TestNotSynchronousOutlining() { using var workspace = TestWorkspace.CreateCSharp("class Program {\r\n\r\n}", composition: EditorTestCompositions.EditorFeaturesWpf); WpfTestRunner.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(TestNotSynchronousOutlining)} creates asynchronous taggers"); var tagProvider = workspace.ExportProvider.GetExportedValue<AbstractStructureTaggerProvider>(); var document = workspace.Documents.First(); var textBuffer = document.GetTextBuffer(); var tagger = tagProvider.CreateTagger<IStructureTag>(textBuffer); Contract.ThrowIfNull(tagger); using var disposable = (IDisposable)tagger; // The very first all to get tags will not be synchronous as this contains no #region tag var tags = tagger.GetTags(new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot.GetFullSpan())); Assert.Equal(0, tags.Count()); } [WpfFact] public void TestSynchronousOutlining() { using var workspace = TestWorkspace.CreateCSharp(@" #region x class Program { } #endregion", composition: EditorTestCompositions.EditorFeaturesWpf); WpfTestRunner.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(TestSynchronousOutlining)} creates asynchronous taggers"); var tagProvider = workspace.ExportProvider.GetExportedValue<AbstractStructureTaggerProvider>(); var document = workspace.Documents.First(); var textBuffer = document.GetTextBuffer(); var tagger = tagProvider.CreateTagger<IStructureTag>(textBuffer); Contract.ThrowIfNull(tagger); using var disposable = (IDisposable)tagger; // The very first all to get tags will be synchronous because of the #region var tags = tagger.GetTags(new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot.GetFullSpan())); Assert.Equal(2, tags.Count()); } private static TestTaggerEventSource CreateEventSource() => new TestTaggerEventSource(); private sealed class TestTag : TextMarkerTag { public TestTag() : base("Test") { } } private delegate List<ITagSpan<TestTag>> Callback(SnapshotSpan span, CancellationToken cancellationToken); private sealed class TestTaggerProvider : AsynchronousTaggerProvider<TestTag> { private readonly Callback _callback; private readonly ITaggerEventSource _eventSource; public TestTaggerProvider( IThreadingContext threadingContext, Callback callback, ITaggerEventSource eventSource, IGlobalOptionService globalOptions, IAsynchronousOperationListener asyncListener) : base(threadingContext, globalOptions, visibilityTracker: null, asyncListener) { _callback = callback; _eventSource = eventSource; } protected override TaggerDelay EventChangeDelay => TaggerDelay.NearImmediate; protected override ITaggerEventSource CreateEventSource(ITextView? textView, ITextBuffer subjectBuffer) => _eventSource; protected override Task ProduceTagsAsync( TaggerContext<TestTag> context, DocumentSnapshotSpan snapshotSpan, int? caretPosition, CancellationToken cancellationToken) { var tags = _callback(snapshotSpan.SnapshotSpan, cancellationToken); if (tags != null) { foreach (var tag in tags) { context.AddTag(tag); } } return Task.CompletedTask; } } private sealed class TestTaggerEventSource : AbstractTaggerEventSource { public TestTaggerEventSource() { } public void SendUpdateEvent() => this.RaiseChanged(); public override void Connect() { } public override void Disconnect() { } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/VisualBasic/Portable/Wrapping/VisualBasicWrappingCodeRefactoringProvider.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 Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping.BinaryExpression Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping.ChainedExpression Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping.SeparatedSyntaxList Imports Microsoft.CodeAnalysis.Wrapping Namespace Microsoft.CodeAnalysis.VisualBasic.Wrapping <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.Wrapping), [Shared]> Friend Class VisualBasicWrappingCodeRefactoringProvider Inherits AbstractWrappingCodeRefactoringProvider Private Shared ReadOnly s_wrappers As ImmutableArray(Of ISyntaxWrapper) = ImmutableArray.Create(Of ISyntaxWrapper)( New VisualBasicArgumentWrapper(), New VisualBasicParameterWrapper(), New VisualBasicBinaryExpressionWrapper(), New VisualBasicChainedExpressionWrapper(), New VisualBasicCollectionCreationExpressionWrapper()) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() MyBase.New(s_wrappers) End Sub Protected Overrides Function GetWrappingOptions(options As AnalyzerConfigOptions, ideOptions As CodeActionOptions) As SyntaxWrappingOptions Return VisualBasicSyntaxWrappingOptions.Create(options, ideOptions) 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.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping.BinaryExpression Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping.ChainedExpression Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping.SeparatedSyntaxList Imports Microsoft.CodeAnalysis.Wrapping Namespace Microsoft.CodeAnalysis.VisualBasic.Wrapping <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.Wrapping), [Shared]> Friend Class VisualBasicWrappingCodeRefactoringProvider Inherits AbstractWrappingCodeRefactoringProvider Private Shared ReadOnly s_wrappers As ImmutableArray(Of ISyntaxWrapper) = ImmutableArray.Create(Of ISyntaxWrapper)( New VisualBasicArgumentWrapper(), New VisualBasicParameterWrapper(), New VisualBasicBinaryExpressionWrapper(), New VisualBasicChainedExpressionWrapper(), New VisualBasicCollectionCreationExpressionWrapper()) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() MyBase.New(s_wrappers) End Sub Protected Overrides Function GetWrappingOptions(options As AnalyzerConfigOptions, ideOptions As CodeActionOptions) As SyntaxWrappingOptions Return VisualBasicSyntaxWrappingOptions.Create(options, ideOptions) End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.InlineDeclaration; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitType; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InlineDeclaration { public partial class CSharpInlineDeclarationTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public CSharpInlineDeclarationTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpInlineDeclarationDiagnosticAnalyzer(), new CSharpInlineDeclarationCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariable1() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineInNestedCall() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; if (Goo(int.TryParse(v, out i))) { } } }", @"class C { void M() { if (Goo(int.TryParse(v, out int i))) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableWithConstructor1() { await TestInRegularAndScript1Async( @"class C1 { public C1(int v, out int i) {} void M(int v) { [|int|] i; if (new C1(v, out i)) { } } }", @"class C1 { public C1(int v, out int i) {} void M(int v) { if (new C1(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableMissingWithIndexer1() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i; if (this[out i]) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableIntoFirstOut1() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableIntoFirstOut2() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInCSharp6() { await TestMissingAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } } }", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariablePreferVar1() { await TestInRegularAndScript1Async( @"class C { void M(string v) { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M(string v) { if (int.TryParse(v, out var i)) { } } }", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere())); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariablePreferVarExceptForPredefinedTypes1() { await TestInRegularAndScript1Async( @"class C { void M(string v) { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M(string v) { if (int.TryParse(v, out int i)) { } } }", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeButKeepIntrinsics())); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableWhenWrittenAfter1() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } i = 0; } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } i = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWhenWrittenBetween1() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i; i = 0; if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWhenReadBetween1() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = 0; M1(i); if (int.TryParse(v, out i)) { } } void M1(int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWithComplexInitializer() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = M1(); if (int.TryParse(v, out i)) { } } int M1() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableInOuterScopeIfNotWrittenOutside() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = 0; { if (int.TryParse(v, out i)) { } i = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfWrittenAfterInOuterScope() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = 0; { if (int.TryParse(v, out i)) { } } i = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfWrittenBetweenInOuterScope() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = 0; { i = 1; if (int.TryParse(v, out i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInNonOut() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInField() { await TestMissingInRegularAndScriptAsync( @"class C { [|int|] i; void M() { if (int.TryParse(v, out this.i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInField2() { await TestMissingInRegularAndScriptAsync( @"class C { [|int|] i; void M() { if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInNonLocalStatement() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { foreach ([|int|] i in e) { if (int.TryParse(v, out i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInEmbeddedStatementWithWriteAfterwards() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i; while (true) if (int.TryParse(v, out i)) { } i = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInEmbeddedStatement() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; while (true) if (int.TryParse(v, out i)) { i = 1; } } }", @"class C { void M() { while (true) if (int.TryParse(v, out int i)) { i = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableInNestedBlock() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; while (true) { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { while (true) { if (int.TryParse(v, out int i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestOverloadResolutionDoNotUseVar1() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; if (M2(out i)) { } } void M2(out int i) { } void M2(out string s) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2(out int i) { } void M2(out string s) { } }", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere())); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestOverloadResolutionDoNotUseVar2() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] i = 0; if (M2(out i)) { } } void M2(out int i) { } void M2(out string s) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2(out int i) { } void M2(out string s) { } }", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere())); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestGenericInferenceDoNotUseVar3() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; if (M2(out i)) { } } void M2<T>(out T i) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2<T>(out T i) { } }", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere())); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments1() { await TestInRegularAndScript1Async( @"class C { void M() { // prefix comment [|int|] i; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // prefix comment { if (int.TryParse(v, out int i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments2() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; // suffix comment { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // suffix comment { if (int.TryParse(v, out int i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments3() { await TestInRegularAndScript1Async( @"class C { void M() { // prefix comment [|int|] i; // suffix comment { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // prefix comment // suffix comment { if (int.TryParse(v, out int i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments4() { await TestInRegularAndScript1Async( @"class C { void M() { int [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int i /*suffix*/)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments5() { await TestInRegularAndScript1Async( @"class C { void M() { int /*prefix*/ [|i|], j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments6() { await TestInRegularAndScript1Async( @"class C { void M() { int /*prefix*/ [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments7() { await TestInRegularAndScript1Async( @"class C { void M() { int j, /*prefix*/ [|i|] /*suffix*/; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments8() { await TestInRegularAndScript1Async( @"class C { void M() { // prefix int j, [|i|]; // suffix { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // prefix int j; // suffix { if (int.TryParse(v, out int i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments9() { await TestInRegularAndScript1Async( @"class C { void M() { int /*int comment*/ /*prefix*/ [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int /*int comment*/ j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }"); } [WorkItem(15994, "https://github.com/dotnet/roslyn/issues/15994")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestCommentsTrivia1() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Goo""); int [|result|]; if (int.TryParse(""12"", out result)) { } } }", @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Goo""); if (int.TryParse(""12"", out int result)) { } } }"); } [WorkItem(15994, "https://github.com/dotnet/roslyn/issues/15994")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestCommentsTrivia2() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Goo""); // Goo int [|result|]; if (int.TryParse(""12"", out result)) { } } }", @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Goo""); // Goo if (int.TryParse(""12"", out int result)) { } } }"); } [WorkItem(15336, "https://github.com/dotnet/roslyn/issues/15336")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotMissingIfCapturedInLambdaAndNotUsedAfterwards() { await TestInRegularAndScript1Async( @" using System; class C { void M() { string [|s|]; Bar(() => Baz(out s)); } void Baz(out string s) { } void Bar(Action a) { } }", @" using System; class C { void M() { Bar(() => Baz(out string s)); } void Baz(out string s) { } void Bar(Action a) { } }"); } [WorkItem(15336, "https://github.com/dotnet/roslyn/issues/15336")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfCapturedInLambdaAndUsedAfterwards() { await TestMissingInRegularAndScriptAsync( @" using System; class C { void M() { string [|s|]; Bar(() => Baz(out s)); Console.WriteLine(s); } void Baz(out string s) { } void Bar(Action a) { } }"); } [WorkItem(15408, "https://github.com/dotnet/roslyn/issues/15408")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDataFlow1() { await TestMissingInRegularAndScriptAsync( @" using System; class C { void Goo(string x) { object [|s|] = null; if (x != null || TryBaz(out s)) { Console.WriteLine(s); } } private bool TryBaz(out object s) { throw new NotImplementedException(); } }"); } [WorkItem(15408, "https://github.com/dotnet/roslyn/issues/15408")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDataFlow2() { await TestInRegularAndScript1Async( @" using System; class C { void Goo(string x) { object [|s|] = null; if (x != null && TryBaz(out s)) { Console.WriteLine(s); } } private bool TryBaz(out object s) { throw new NotImplementedException(); } }", @" using System; class C { void Goo(string x) { if (x != null && TryBaz(out object s)) { Console.WriteLine(s); } } private bool TryBaz(out object s) { throw new NotImplementedException(); } }"); } [WorkItem(16028, "https://github.com/dotnet/roslyn/issues/16028")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestExpressionTree1() { await TestMissingInRegularAndScriptAsync( @" using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { int [|result|]; Method(() => GetValue(out result)); } public static void GetValue(out int result) { result = 0; } public static void Method(Expression<Action> expression) { } }"); } [WorkItem(16198, "https://github.com/dotnet/roslyn/issues/16198")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestIndentation1() { await TestInRegularAndScript1Async( @" using System; class C { private int Bar() { IProjectRuleSnapshot [|unresolvedReferenceSnapshot|] = null; var itemType = GetUnresolvedReferenceItemType(originalItemSpec, updatedUnresolvedSnapshots, catalogs, out unresolvedReferenceSnapshot); } }", @" using System; class C { private int Bar() { var itemType = GetUnresolvedReferenceItemType(originalItemSpec, updatedUnresolvedSnapshots, catalogs, out IProjectRuleSnapshot unresolvedReferenceSnapshot); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInLoops1() { await TestMissingAsync( @" using System; class C { static void Main(string[] args) { string [|token|]; do { } while (!TryExtractTokenFromEmail(out token)); Console.WriteLine(token == ""Test""); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInLoops2() { await TestMissingAsync( @" using System; class C { static void Main(string[] args) { string [|token|]; while (!TryExtractTokenFromEmail(out token)) { } Console.WriteLine(token == ""Test""); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInLoops3() { await TestMissingAsync( @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { string [|token|]; foreach (var v in TryExtractTokenFromEmail(out token)) { } Console.WriteLine(token == ""Test""); } private static IEnumerable<bool> TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInLoops4() { await TestMissingAsync( @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { string [|token|]; for ( ; TryExtractTokenFromEmail(out token); ) { } Console.WriteLine(token == ""Test""); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInUsing() { await TestMissingAsync( @" using System; class C { static void Main(string[] args) { string [|token|]; using (GetDisposableAndValue(out token)) { } Console.WriteLine(token); } private static IDisposable GetDisposableAndValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInExceptionFilter() { await TestMissingAsync( @" using System; class C { static void Main(string[] args) { string [|token|]; try { } catch when (GetValue(out token)) { } Console.WriteLine(token); } private static bool GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInShortCircuitExpression1() { await TestMissingAsync( @" using System; class C { static void Main(string[] args) { string [|token|] = null; bool condition = false && GetValue(out token); Console.WriteLine(token); } private static bool GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInShortCircuitExpression2() { await TestMissingAsync( @" using System; class C { static void Main(string[] args) { string [|token|]; bool condition = false && GetValue(out token); Console.WriteLine(token); } private static bool GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInFixed() { await TestMissingAsync( @" using System; class C { static unsafe void Main(string[] args) { string [|token|]; fixed (int* p = GetValue(out token)) { } Console.WriteLine(token); } private static int[] GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLoops1() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|]; do { } while (!TryExtractTokenFromEmail(out token)); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { do { } while (!TryExtractTokenFromEmail(out string token)); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLoops2() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|]; while (!TryExtractTokenFromEmail(out token)) { } } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { while (!TryExtractTokenFromEmail(out string token)) { } } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLoops3() { await TestInRegularAndScript1Async( @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { string [|token|]; foreach (var v in TryExtractTokenFromEmail(out token)) { } } private static IEnumerable<bool> TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }", @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { foreach (var v in TryExtractTokenFromEmail(out string token)) { } } private static IEnumerable<bool> TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLoops4() { await TestInRegularAndScript1Async( @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { string [|token|]; for ( ; TryExtractTokenFromEmail(out token); ) { } } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }", @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { for (; TryExtractTokenFromEmail(out string token);) { } } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInUsing() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|]; using (GetDisposableAndValue(out token)) { } } private static IDisposable GetDisposableAndValue(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { using (GetDisposableAndValue(out string token)) { } } private static IDisposable GetDisposableAndValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInExceptionFilter() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|]; try { } catch when (GetValue(out token)) { } } private static bool GetValue(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { try { } catch when (GetValue(out string token)) { } } private static bool GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInShortCircuitExpression1() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|] = null; bool condition = false && GetValue(out token); } private static bool GetValue(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { bool condition = false && GetValue(out string token); } private static bool GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInShortCircuitExpression2() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|]; bool condition = false && GetValue(out token); } private static bool GetValue(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { bool condition = false && GetValue(out string token); } private static bool GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInFixed() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|]; fixed (int* p = GetValue(out token)) { } } private static int[] GetValue(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { fixed (int* p = GetValue(out string token)) { } } private static int[] GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17743, "https://github.com/dotnet/roslyn/issues/17743")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLocalFunction1() { await TestMissingInRegularAndScriptAsync( @" using System; using System.Collections.Generic; class Demo { static void Main() { F(); void F() { Action f = () => { Dictionary<int, int> dict = null; int [|x|] = 0; dict?.TryGetValue(0, out x); Console.WriteLine(x); }; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLocalFunction2() { await TestInRegularAndScript1Async( @" using System; using System.Collections.Generic; class Demo { static void Main() { F(); void F() { Action f = () => { Dictionary<int, int> dict = null; int [|x|] = 0; dict.TryGetValue(0, out x); Console.WriteLine(x); }; } } }", @" using System; using System.Collections.Generic; class Demo { static void Main() { F(); void F() { Action f = () => { Dictionary<int, int> dict = null; dict.TryGetValue(0, out int x); Console.WriteLine(x); }; } } }"); } [WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMultipleDeclarationStatementsOnSameLine1() { await TestInRegularAndScript1Async( @" class C { void Goo() { string a; string [|b|]; Method(out a, out b); } }", @" class C { void Goo() { string a; Method(out a, out string b); } }"); } [WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMultipleDeclarationStatementsOnSameLine2() { await TestInRegularAndScript1Async( @" class C { void Goo() { string a; /*leading*/ string [|b|]; // trailing Method(out a, out b); } }", @" class C { void Goo() { string a; /*leading*/ // trailing Method(out a, out string b); } }"); } [WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMultipleDeclarationStatementsOnSameLine3() { await TestInRegularAndScript1Async( @" class C { void Goo() { string a; /*leading*/ string [|b|]; // trailing Method(out a, out b); } }", @" class C { void Goo() { string a; /*leading*/ // trailing Method(out a, out string b); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingOnUnderscore() { await TestMissingInRegularAndScriptAsync( @" using System; class C { void M() { [|int|] _; if (N(out _) { Console.WriteLine(_); } } }"); } [WorkItem(18668, "https://github.com/dotnet/roslyn/issues/18668")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDefiniteAssignmentIssueWithVar() { await TestMissingInRegularAndScriptAsync( @" using System; class C { static void M(bool condition) { [|var|] x = 1; var result = condition && int.TryParse(""2"", out x); Console.WriteLine(x); } }"); } [WorkItem(18668, "https://github.com/dotnet/roslyn/issues/18668")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDefiniteAssignmentIssueWithNonVar() { await TestMissingInRegularAndScriptAsync( @" using System; class C { static void M(bool condition) { [|int|] x = 1; var result = condition && int.TryParse(""2"", out x); Console.WriteLine(x); } }"); } [WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingOnCrossFunction1() { await TestMissingInRegularAndScriptAsync( @" using System; class Program { static void Main(string[] args) { Method<string>(); } public static void Method<T>() { [|T t|]; void Local<T>() { Out(out t); Console.WriteLine(t); } Local<int>(); } public static void Out<T>(out T t) => t = default; }"); } [WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingOnCrossFunction2() { await TestMissingInRegularAndScriptAsync( @" using System; class Program { static void Main(string[] args) { Method<string>(); } public static void Method<T>() { void Local<T>() { [|T t|]; void InnerLocal<T>() { Out(out t); Console.WriteLine(t); } } Local<int>(); } public static void Out<T>(out T t) => t = default; }"); } [WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingOnCrossFunction3() { await TestMissingInRegularAndScriptAsync( @" using System; class Program { static void Main(string[] args) { Method<string>(); } public static void Method<T>() { [|T t|]; void Local<T>() { { // <-- note this set of added braces Out(out t); Console.WriteLine(t); } } Local<int>(); } public static void Out<T>(out T t) => t = default; }"); } [WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingOnCrossFunction4() { await TestMissingInRegularAndScriptAsync( @" using System; class Program { static void Main(string[] args) { Method<string>(); } public static void Method<T>() { { // <-- note this set of added braces [|T t|]; void Local<T>() { { // <-- and my axe Out(out t); Console.WriteLine(t); } } Local<int>(); } } public static void Out<T>(out T t) => t = default; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDefiniteAssignment1() { await TestMissingInRegularAndScriptAsync( @" using System; class C { static bool M(out bool i) => throw null; static void M(bool condition) { [|bool|] x = false; if (condition || M(out x)) { Console.WriteLine(x); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDefiniteAssignment2() { await TestMissingInRegularAndScriptAsync( @" using System; class C { static bool M(out bool i) => throw null; static bool Use(bool i) => throw null; static void M(bool condition) { [|bool|] x = false; if (condition || M(out x)) { x = Use(x); } } }"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [InlineData("c && M(out x)", "c && M(out bool x)")] [InlineData("false || M(out x)", "false || M(out bool x)")] [InlineData("M(out x) || M(out x)", "M(out bool x) || M(out x)")] public async Task TestDefiniteAssignment3(string input, string output) { await TestInRegularAndScript1Async( $@" using System; class C {{ static bool M(out bool i) => throw null; static bool Use(bool i) => throw null; static void M(bool c) {{ [|bool|] x = false; if ({input}) {{ Console.WriteLine(x); }} }} }}", $@" using System; class C {{ static bool M(out bool i) => throw null; static bool Use(bool i) => throw null; static void M(bool c) {{ if ({output}) {{ Console.WriteLine(x); }} }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariable_NullableEnable() { await TestInRegularAndScript1Async(@" #nullable enable class C { void M(out C c2) { [|C|] c; M(out c); c2 = c; } }", @" #nullable enable class C { void M(out C c2) { M(out C c); c2 = c; } }"); } [WorkItem(44429, "https://github.com/dotnet/roslyn/issues/44429")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TopLevelStatement() { await TestMissingAsync(@" [|int|] i; if (int.TryParse(v, out i)) { }", new TestParameters(TestOptions.Regular)); } [WorkItem(47041, "https://github.com/dotnet/roslyn/issues/47041")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task CollectionInitializer() { await TestInRegularAndScript1Async( @"class C { private List<Func<string, bool>> _funcs2 = new List<Func<string, bool>>() { s => { int [|i|] = 0; return int.TryParse(s, out i); } }; }", @"class C { private List<Func<string, bool>> _funcs2 = new List<Func<string, bool>>() { s => { return int.TryParse(s, out int i); } }; }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.InlineDeclaration; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitType; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InlineDeclaration { public partial class CSharpInlineDeclarationTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public CSharpInlineDeclarationTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpInlineDeclarationDiagnosticAnalyzer(), new CSharpInlineDeclarationCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariable1() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineInNestedCall() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; if (Goo(int.TryParse(v, out i))) { } } }", @"class C { void M() { if (Goo(int.TryParse(v, out int i))) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableWithConstructor1() { await TestInRegularAndScript1Async( @"class C1 { public C1(int v, out int i) {} void M(int v) { [|int|] i; if (new C1(v, out i)) { } } }", @"class C1 { public C1(int v, out int i) {} void M(int v) { if (new C1(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableMissingWithIndexer1() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i; if (this[out i]) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableIntoFirstOut1() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableIntoFirstOut2() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInCSharp6() { await TestMissingAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } } }", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariablePreferVar1() { await TestInRegularAndScript1Async( @"class C { void M(string v) { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M(string v) { if (int.TryParse(v, out var i)) { } } }", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere())); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariablePreferVarExceptForPredefinedTypes1() { await TestInRegularAndScript1Async( @"class C { void M(string v) { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M(string v) { if (int.TryParse(v, out int i)) { } } }", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeButKeepIntrinsics())); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableWhenWrittenAfter1() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } i = 0; } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } i = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWhenWrittenBetween1() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i; i = 0; if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWhenReadBetween1() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = 0; M1(i); if (int.TryParse(v, out i)) { } } void M1(int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWithComplexInitializer() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = M1(); if (int.TryParse(v, out i)) { } } int M1() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableInOuterScopeIfNotWrittenOutside() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = 0; { if (int.TryParse(v, out i)) { } i = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfWrittenAfterInOuterScope() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = 0; { if (int.TryParse(v, out i)) { } } i = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfWrittenBetweenInOuterScope() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = 0; { i = 1; if (int.TryParse(v, out i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInNonOut() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInField() { await TestMissingInRegularAndScriptAsync( @"class C { [|int|] i; void M() { if (int.TryParse(v, out this.i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInField2() { await TestMissingInRegularAndScriptAsync( @"class C { [|int|] i; void M() { if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInNonLocalStatement() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { foreach ([|int|] i in e) { if (int.TryParse(v, out i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInEmbeddedStatementWithWriteAfterwards() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i; while (true) if (int.TryParse(v, out i)) { } i = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInEmbeddedStatement() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; while (true) if (int.TryParse(v, out i)) { i = 1; } } }", @"class C { void M() { while (true) if (int.TryParse(v, out int i)) { i = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableInNestedBlock() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; while (true) { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { while (true) { if (int.TryParse(v, out int i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestOverloadResolutionDoNotUseVar1() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; if (M2(out i)) { } } void M2(out int i) { } void M2(out string s) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2(out int i) { } void M2(out string s) { } }", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere())); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestOverloadResolutionDoNotUseVar2() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] i = 0; if (M2(out i)) { } } void M2(out int i) { } void M2(out string s) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2(out int i) { } void M2(out string s) { } }", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere())); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestGenericInferenceDoNotUseVar3() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; if (M2(out i)) { } } void M2<T>(out T i) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2<T>(out T i) { } }", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere())); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments1() { await TestInRegularAndScript1Async( @"class C { void M() { // prefix comment [|int|] i; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // prefix comment { if (int.TryParse(v, out int i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments2() { await TestInRegularAndScript1Async( @"class C { void M() { [|int|] i; // suffix comment { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // suffix comment { if (int.TryParse(v, out int i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments3() { await TestInRegularAndScript1Async( @"class C { void M() { // prefix comment [|int|] i; // suffix comment { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // prefix comment // suffix comment { if (int.TryParse(v, out int i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments4() { await TestInRegularAndScript1Async( @"class C { void M() { int [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int i /*suffix*/)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments5() { await TestInRegularAndScript1Async( @"class C { void M() { int /*prefix*/ [|i|], j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments6() { await TestInRegularAndScript1Async( @"class C { void M() { int /*prefix*/ [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments7() { await TestInRegularAndScript1Async( @"class C { void M() { int j, /*prefix*/ [|i|] /*suffix*/; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments8() { await TestInRegularAndScript1Async( @"class C { void M() { // prefix int j, [|i|]; // suffix { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // prefix int j; // suffix { if (int.TryParse(v, out int i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments9() { await TestInRegularAndScript1Async( @"class C { void M() { int /*int comment*/ /*prefix*/ [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int /*int comment*/ j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }"); } [WorkItem(15994, "https://github.com/dotnet/roslyn/issues/15994")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestCommentsTrivia1() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Goo""); int [|result|]; if (int.TryParse(""12"", out result)) { } } }", @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Goo""); if (int.TryParse(""12"", out int result)) { } } }"); } [WorkItem(15994, "https://github.com/dotnet/roslyn/issues/15994")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestCommentsTrivia2() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Goo""); // Goo int [|result|]; if (int.TryParse(""12"", out result)) { } } }", @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Goo""); // Goo if (int.TryParse(""12"", out int result)) { } } }"); } [WorkItem(15336, "https://github.com/dotnet/roslyn/issues/15336")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotMissingIfCapturedInLambdaAndNotUsedAfterwards() { await TestInRegularAndScript1Async( @" using System; class C { void M() { string [|s|]; Bar(() => Baz(out s)); } void Baz(out string s) { } void Bar(Action a) { } }", @" using System; class C { void M() { Bar(() => Baz(out string s)); } void Baz(out string s) { } void Bar(Action a) { } }"); } [WorkItem(15336, "https://github.com/dotnet/roslyn/issues/15336")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfCapturedInLambdaAndUsedAfterwards() { await TestMissingInRegularAndScriptAsync( @" using System; class C { void M() { string [|s|]; Bar(() => Baz(out s)); Console.WriteLine(s); } void Baz(out string s) { } void Bar(Action a) { } }"); } [WorkItem(15408, "https://github.com/dotnet/roslyn/issues/15408")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDataFlow1() { await TestMissingInRegularAndScriptAsync( @" using System; class C { void Goo(string x) { object [|s|] = null; if (x != null || TryBaz(out s)) { Console.WriteLine(s); } } private bool TryBaz(out object s) { throw new NotImplementedException(); } }"); } [WorkItem(15408, "https://github.com/dotnet/roslyn/issues/15408")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDataFlow2() { await TestInRegularAndScript1Async( @" using System; class C { void Goo(string x) { object [|s|] = null; if (x != null && TryBaz(out s)) { Console.WriteLine(s); } } private bool TryBaz(out object s) { throw new NotImplementedException(); } }", @" using System; class C { void Goo(string x) { if (x != null && TryBaz(out object s)) { Console.WriteLine(s); } } private bool TryBaz(out object s) { throw new NotImplementedException(); } }"); } [WorkItem(16028, "https://github.com/dotnet/roslyn/issues/16028")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestExpressionTree1() { await TestMissingInRegularAndScriptAsync( @" using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { int [|result|]; Method(() => GetValue(out result)); } public static void GetValue(out int result) { result = 0; } public static void Method(Expression<Action> expression) { } }"); } [WorkItem(16198, "https://github.com/dotnet/roslyn/issues/16198")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestIndentation1() { await TestInRegularAndScript1Async( @" using System; class C { private int Bar() { IProjectRuleSnapshot [|unresolvedReferenceSnapshot|] = null; var itemType = GetUnresolvedReferenceItemType(originalItemSpec, updatedUnresolvedSnapshots, catalogs, out unresolvedReferenceSnapshot); } }", @" using System; class C { private int Bar() { var itemType = GetUnresolvedReferenceItemType(originalItemSpec, updatedUnresolvedSnapshots, catalogs, out IProjectRuleSnapshot unresolvedReferenceSnapshot); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInLoops1() { await TestMissingAsync( @" using System; class C { static void Main(string[] args) { string [|token|]; do { } while (!TryExtractTokenFromEmail(out token)); Console.WriteLine(token == ""Test""); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInLoops2() { await TestMissingAsync( @" using System; class C { static void Main(string[] args) { string [|token|]; while (!TryExtractTokenFromEmail(out token)) { } Console.WriteLine(token == ""Test""); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInLoops3() { await TestMissingAsync( @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { string [|token|]; foreach (var v in TryExtractTokenFromEmail(out token)) { } Console.WriteLine(token == ""Test""); } private static IEnumerable<bool> TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInLoops4() { await TestMissingAsync( @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { string [|token|]; for ( ; TryExtractTokenFromEmail(out token); ) { } Console.WriteLine(token == ""Test""); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInUsing() { await TestMissingAsync( @" using System; class C { static void Main(string[] args) { string [|token|]; using (GetDisposableAndValue(out token)) { } Console.WriteLine(token); } private static IDisposable GetDisposableAndValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInExceptionFilter() { await TestMissingAsync( @" using System; class C { static void Main(string[] args) { string [|token|]; try { } catch when (GetValue(out token)) { } Console.WriteLine(token); } private static bool GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInShortCircuitExpression1() { await TestMissingAsync( @" using System; class C { static void Main(string[] args) { string [|token|] = null; bool condition = false && GetValue(out token); Console.WriteLine(token); } private static bool GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInShortCircuitExpression2() { await TestMissingAsync( @" using System; class C { static void Main(string[] args) { string [|token|]; bool condition = false && GetValue(out token); Console.WriteLine(token); } private static bool GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInFixed() { await TestMissingAsync( @" using System; class C { static unsafe void Main(string[] args) { string [|token|]; fixed (int* p = GetValue(out token)) { } Console.WriteLine(token); } private static int[] GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLoops1() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|]; do { } while (!TryExtractTokenFromEmail(out token)); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { do { } while (!TryExtractTokenFromEmail(out string token)); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLoops2() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|]; while (!TryExtractTokenFromEmail(out token)) { } } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { while (!TryExtractTokenFromEmail(out string token)) { } } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLoops3() { await TestInRegularAndScript1Async( @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { string [|token|]; foreach (var v in TryExtractTokenFromEmail(out token)) { } } private static IEnumerable<bool> TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }", @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { foreach (var v in TryExtractTokenFromEmail(out string token)) { } } private static IEnumerable<bool> TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLoops4() { await TestInRegularAndScript1Async( @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { string [|token|]; for ( ; TryExtractTokenFromEmail(out token); ) { } } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }", @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { for (; TryExtractTokenFromEmail(out string token);) { } } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInUsing() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|]; using (GetDisposableAndValue(out token)) { } } private static IDisposable GetDisposableAndValue(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { using (GetDisposableAndValue(out string token)) { } } private static IDisposable GetDisposableAndValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInExceptionFilter() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|]; try { } catch when (GetValue(out token)) { } } private static bool GetValue(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { try { } catch when (GetValue(out string token)) { } } private static bool GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInShortCircuitExpression1() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|] = null; bool condition = false && GetValue(out token); } private static bool GetValue(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { bool condition = false && GetValue(out string token); } private static bool GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInShortCircuitExpression2() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|]; bool condition = false && GetValue(out token); } private static bool GetValue(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { bool condition = false && GetValue(out string token); } private static bool GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInFixed() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|]; fixed (int* p = GetValue(out token)) { } } private static int[] GetValue(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { fixed (int* p = GetValue(out string token)) { } } private static int[] GetValue(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17743, "https://github.com/dotnet/roslyn/issues/17743")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLocalFunction1() { await TestMissingInRegularAndScriptAsync( @" using System; using System.Collections.Generic; class Demo { static void Main() { F(); void F() { Action f = () => { Dictionary<int, int> dict = null; int [|x|] = 0; dict?.TryGetValue(0, out x); Console.WriteLine(x); }; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLocalFunction2() { await TestInRegularAndScript1Async( @" using System; using System.Collections.Generic; class Demo { static void Main() { F(); void F() { Action f = () => { Dictionary<int, int> dict = null; int [|x|] = 0; dict.TryGetValue(0, out x); Console.WriteLine(x); }; } } }", @" using System; using System.Collections.Generic; class Demo { static void Main() { F(); void F() { Action f = () => { Dictionary<int, int> dict = null; dict.TryGetValue(0, out int x); Console.WriteLine(x); }; } } }"); } [WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMultipleDeclarationStatementsOnSameLine1() { await TestInRegularAndScript1Async( @" class C { void Goo() { string a; string [|b|]; Method(out a, out b); } }", @" class C { void Goo() { string a; Method(out a, out string b); } }"); } [WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMultipleDeclarationStatementsOnSameLine2() { await TestInRegularAndScript1Async( @" class C { void Goo() { string a; /*leading*/ string [|b|]; // trailing Method(out a, out b); } }", @" class C { void Goo() { string a; /*leading*/ // trailing Method(out a, out string b); } }"); } [WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMultipleDeclarationStatementsOnSameLine3() { await TestInRegularAndScript1Async( @" class C { void Goo() { string a; /*leading*/ string [|b|]; // trailing Method(out a, out b); } }", @" class C { void Goo() { string a; /*leading*/ // trailing Method(out a, out string b); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingOnUnderscore() { await TestMissingInRegularAndScriptAsync( @" using System; class C { void M() { [|int|] _; if (N(out _) { Console.WriteLine(_); } } }"); } [WorkItem(18668, "https://github.com/dotnet/roslyn/issues/18668")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDefiniteAssignmentIssueWithVar() { await TestMissingInRegularAndScriptAsync( @" using System; class C { static void M(bool condition) { [|var|] x = 1; var result = condition && int.TryParse(""2"", out x); Console.WriteLine(x); } }"); } [WorkItem(18668, "https://github.com/dotnet/roslyn/issues/18668")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDefiniteAssignmentIssueWithNonVar() { await TestMissingInRegularAndScriptAsync( @" using System; class C { static void M(bool condition) { [|int|] x = 1; var result = condition && int.TryParse(""2"", out x); Console.WriteLine(x); } }"); } [WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingOnCrossFunction1() { await TestMissingInRegularAndScriptAsync( @" using System; class Program { static void Main(string[] args) { Method<string>(); } public static void Method<T>() { [|T t|]; void Local<T>() { Out(out t); Console.WriteLine(t); } Local<int>(); } public static void Out<T>(out T t) => t = default; }"); } [WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingOnCrossFunction2() { await TestMissingInRegularAndScriptAsync( @" using System; class Program { static void Main(string[] args) { Method<string>(); } public static void Method<T>() { void Local<T>() { [|T t|]; void InnerLocal<T>() { Out(out t); Console.WriteLine(t); } } Local<int>(); } public static void Out<T>(out T t) => t = default; }"); } [WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingOnCrossFunction3() { await TestMissingInRegularAndScriptAsync( @" using System; class Program { static void Main(string[] args) { Method<string>(); } public static void Method<T>() { [|T t|]; void Local<T>() { { // <-- note this set of added braces Out(out t); Console.WriteLine(t); } } Local<int>(); } public static void Out<T>(out T t) => t = default; }"); } [WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingOnCrossFunction4() { await TestMissingInRegularAndScriptAsync( @" using System; class Program { static void Main(string[] args) { Method<string>(); } public static void Method<T>() { { // <-- note this set of added braces [|T t|]; void Local<T>() { { // <-- and my axe Out(out t); Console.WriteLine(t); } } Local<int>(); } } public static void Out<T>(out T t) => t = default; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDefiniteAssignment1() { await TestMissingInRegularAndScriptAsync( @" using System; class C { static bool M(out bool i) => throw null; static void M(bool condition) { [|bool|] x = false; if (condition || M(out x)) { Console.WriteLine(x); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDefiniteAssignment2() { await TestMissingInRegularAndScriptAsync( @" using System; class C { static bool M(out bool i) => throw null; static bool Use(bool i) => throw null; static void M(bool condition) { [|bool|] x = false; if (condition || M(out x)) { x = Use(x); } } }"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [InlineData("c && M(out x)", "c && M(out bool x)")] [InlineData("false || M(out x)", "false || M(out bool x)")] [InlineData("M(out x) || M(out x)", "M(out bool x) || M(out x)")] public async Task TestDefiniteAssignment3(string input, string output) { await TestInRegularAndScript1Async( $@" using System; class C {{ static bool M(out bool i) => throw null; static bool Use(bool i) => throw null; static void M(bool c) {{ [|bool|] x = false; if ({input}) {{ Console.WriteLine(x); }} }} }}", $@" using System; class C {{ static bool M(out bool i) => throw null; static bool Use(bool i) => throw null; static void M(bool c) {{ if ({output}) {{ Console.WriteLine(x); }} }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariable_NullableEnable() { await TestInRegularAndScript1Async(@" #nullable enable class C { void M(out C c2) { [|C|] c; M(out c); c2 = c; } }", @" #nullable enable class C { void M(out C c2) { M(out C c); c2 = c; } }"); } [WorkItem(44429, "https://github.com/dotnet/roslyn/issues/44429")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TopLevelStatement() { await TestMissingAsync(@" [|int|] i; if (int.TryParse(v, out i)) { }", new TestParameters(TestOptions.Regular)); } [WorkItem(47041, "https://github.com/dotnet/roslyn/issues/47041")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task CollectionInitializer() { await TestInRegularAndScript1Async( @"class C { private List<Func<string, bool>> _funcs2 = new List<Func<string, bool>>() { s => { int [|i|] = 0; return int.TryParse(s, out i); } }; }", @"class C { private List<Func<string, bool>> _funcs2 = new List<Func<string, bool>>() { s => { return int.TryParse(s, out int i); } }; }"); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/SymbolMatcherTests.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.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Roslyn.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports System.Threading.Tasks Imports System.Threading Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SymbolMatcherTests Inherits EditAndContinueTestBase <Fact> Public Sub ConcurrentAccess() Dim source = " Class A Dim F As B Property P As D Sub M(a As A, b As B, s As S, i As I) : End Sub Delegate Sub D(s As S) Class B : End Class Structure S : End Structure Interface I : End Interface End Class Class B Function M(Of T, U)() As A Return Nothing End Function Event E As D Delegate Sub D(s As S) Structure S : End Structure Interface I : End Interface End Class" Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim builder = New List(Of Symbol)() Dim type = compilation1.GetMember(Of NamedTypeSymbol)("A") builder.Add(type) builder.AddRange(type.GetMembers()) type = compilation1.GetMember(Of NamedTypeSymbol)("B") builder.Add(type) builder.AddRange(type.GetMembers()) Dim members = builder.ToImmutableArray() Assert.True(members.Length > 10) For i = 0 To 10 - 1 Dim matcher = CreateMatcher(compilation1, compilation0) Dim tasks(10) As Task For j = 0 To tasks.Length - 1 Dim startAt As Integer = i + j + 1 tasks(j) = Task.Run(Sub() MatchAll(matcher, members, startAt) Thread.Sleep(10) End Sub) Next Task.WaitAll(tasks) Next End Sub Private Shared Sub MatchAll(matcher As VisualBasicSymbolMatcher, members As ImmutableArray(Of Symbol), startAt As Integer) Dim n As Integer = members.Length For i = 0 To n - 1 Dim member = members((i + startAt) Mod n) Dim other = matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IDefinition)) Assert.NotNull(other) Next End Sub <Fact> Public Sub TypeArguments() Dim source = " Class A(Of T) Class B(Of U) Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of Object).S) As A(Of V) Return Nothing End Function Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of V).S) As A(Of V) Return Nothing End Function End Class Structure S End Structure End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim matcher = CreateMatcher(compilation1, compilation0) Dim members = compilation1.GetMember(Of NamedTypeSymbol)("A.B").GetMembers("M") Assert.Equal(members.Length, 2) For Each member In members Dim other = matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IMethodDefinition)) Assert.NotNull(other) Next End Sub <Fact> Public Sub Constraints() Dim source = " Interface I(Of T AS I(Of T)) End Interface Class C Shared Sub M(Of T As I(Of T))(o As I(Of T)) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source) Dim matcher = CreateMatcher(compilation1, compilation0) Dim member = compilation1.GetMember(Of MethodSymbol)("C.M") Dim other = matcher.MapDefinition(member.GetCciAdapter()) Assert.NotNull(other) End Sub <Fact> Public Sub CustomModifiers() Dim ilSource = " .class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F(int32 modopt(object) p) { } } " Dim metadataRef = CompileIL(ilSource) Dim source = " Class B Inherits A Public Overrides Function F(p As Integer) As Object() Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, references:={metadataRef}) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim member1 = compilation1.GetMember(Of MethodSymbol)("B.F") Assert.Equal(DirectCast(member1.ReturnType, ArrayTypeSymbol).CustomModifiers.Length, 1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim other = DirectCast(matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) Assert.Equal(DirectCast(other.ReturnType, ArrayTypeSymbol).CustomModifiers.Length, 1) End Sub <Fact> Public Sub VaryingCompilationReferences() Dim libSource = " Public Class D End Class " Dim source = " Public Class C Public Sub F(a As D) End Sub End Class " Dim lib0 = CreateCompilationWithMscorlib40({libSource}, options:=TestOptions.DebugDll, assemblyName:="Lib") Dim lib1 = CreateCompilationWithMscorlib40({libSource}, options:=TestOptions.DebugDll, assemblyName:="Lib") Dim compilation0 = CreateCompilationWithMscorlib40({source}, {lib0.ToMetadataReference()}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source).WithReferences(MscorlibRef, lib1.ToMetadataReference()) Dim matcher = CreateMatcher(compilation1, compilation0) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim mf1 = matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol() Assert.Equal(f0, mf1) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub PreviousType_ArrayType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As Integer = 0 End Sub Class D : End Class End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x() As D = Nothing End Sub Class D : End Class End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim elementType = compilation1.GetMember(Of TypeSymbol)("C.D") Dim member = compilation1.CreateArrayTypeSymbol(elementType) Dim other = matcher.MapReference(member.GetCciAdapter()) Assert.NotNull(other) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub NoPreviousType_ArrayType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As Integer = 0 End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x() As D = Nothing End Sub Class D : End Class End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim elementType = compilation1.GetMember(Of TypeSymbol)("C.D") Dim member = compilation1.CreateArrayTypeSymbol(elementType) Dim other = matcher.MapReference(member.GetCciAdapter()) ' For a newly added type, there is no match in the previous generation. Assert.Null(other) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub NoPreviousType_GenericType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Class C Shared Sub M() Dim x As Integer = 0 End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Class C Shared Sub M() Dim x As List(Of D) = Nothing End Sub Class D : End Class Dim y As List(Of D) End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim member = compilation1.GetMember(Of FieldSymbol)("C.y") Dim other = matcher.MapReference(DirectCast(member.Type.GetCciAdapter(), Cci.ITypeReference)) ' For a newly added type, there is no match in the previous generation. Assert.Null(other) End Sub <Fact> Public Sub HoistedAnonymousTypes() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = New With { .A = 1 } Dim x2 = New With { .B = 1 } Dim y = New Func(Of Integer)(Function() x1.A + x2.B) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = New With { .A = 1 } Dim x2 = New With { .C = 1 } Dim y = New Func(Of Integer)(Function() x1.A + x2.C) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousType_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("B", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal(2, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single() Assert.Equal("_Closure$__1-0", displayClass.Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClass.GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub HoistedAnonymousTypes_Complex() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = { New With { .A = New With { .X = 1 } } } Dim x2 = { New With { .A = New With { .Y = 1 } } } Dim y = New Func(Of Integer)(Function() x1(0).A.X + x2(0).A.Y) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = { New With { .A = New With { .X = 1 } } } Dim x2 = { New With { .A = New With { .Z = 1 } } } Dim y = New Func(Of Integer)(Function() x1(0).A.X + x2(0).A.Z) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousType_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("X", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_2", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("Y", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal(3, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single() Assert.Equal("_Closure$__1-0", displayClass.Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClass.GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub HoistedAnonymousDelegate() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = Function(a As Integer) 1 Dim x2 = Function(b As Integer) 1 Dim y = New Func(Of Integer)(Function() x1(1) + x2(1)) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = Function(a As Integer) 1 Dim x2 = Function(c As Integer) 1 Dim y = New Func(Of Integer)(Function() x1(1) + x2(1)) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousDelegate_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create( New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True), New AnonymousTypeKeyField(AnonymousTypeDescriptor.FunctionReturnParameterName, isKey:=False, ignoreCase:=True)), isDelegate:=True)).Name) Assert.Equal("VB$AnonymousDelegate_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create( New AnonymousTypeKeyField("B", isKey:=False, ignoreCase:=True), New AnonymousTypeKeyField(AnonymousTypeDescriptor.FunctionReturnParameterName, isKey:=False, ignoreCase:=True)), isDelegate:=True)).Name) Assert.Equal(2, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClasses = peAssemblyBuilder.GetSynthesizedTypes(c).ToArray() Assert.Equal("_Closure$__", displayClasses(0).Name) Assert.Equal("_Closure$__1-0", displayClasses(1).Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClasses(1).GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub Method_RenameParameter() Dim source0 = " Class C Public Function X(a As Integer) As Integer Return a End Function End Class " Dim source1 = " Class C Public Function X(b As Integer) As Integer Return b End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) Assert.NotNull(other) End Sub <Fact> Public Sub TupleField_TypeChange() Dim source0 = " Class C { Public x As (a As Integer, b As Integer) }" Dim source1 = " Class C { Public x As (a As Integer, b As Boolean) }" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("C.x") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleField_NameChange() Dim source0 = " Class C { Public x As (a As Integer, b As Integer) }" Dim source1 = " Class C { Public x As (a As Integer, c As Integer) }" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("C.x") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceFieldSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.x As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleMethod_TypeToNoTupleChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As Integer() Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types should not match: one is tuple and another is not. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_TypeFromNoTupleChange() Dim source0 = " Class C Public Function X() As Integer() Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, b As Boolean) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types should not match: one is tuple and another is not. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_TypeChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, b As Boolean) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_NameChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, c As Integer) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceMemberMethodSymbol) Assert.NotNull(otherSymbol) Assert.Equal("Function C.X() As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleProperty_TypeChange() Dim source0 = " Class C Public ReadOnly Property X As (a As Integer, b As Integer) Get Return Nothing End Get End Property End Class " Dim source1 = " Class C Public ReadOnly Property X As (a As Integer, b As Boolean) Get Return Nothing End Get End Property End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of PropertySymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleProperty_NameChange() Dim source0 = " Class C Public ReadOnly Property X As (a As Integer, b As Integer) Get Return Nothing End Get End Property End Class " Dim source1 = " Class C Public ReadOnly Property X As (a As Integer, c As Integer) Get Return Nothing End Get End Property End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of PropertySymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourcePropertySymbol) Assert.NotNull(otherSymbol) Assert.Equal("ReadOnly Property C.X As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleStructField_TypeChange() Dim source0 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer) End Structure " Dim source1 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer, z As Integer) End Structure " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("Vector.Coordinates") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleStructField_NameChange() Dim source0 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer) End Structure " Dim source1 = " Public Structure Vector Public Coordinates As (x As Integer, z As Integer) End Structure " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("Vector.Coordinates") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceFieldSymbol) Assert.NotNull(otherSymbol) Assert.Equal("Vector.Coordinates As (x As System.Int32, y As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleDelegate_TypeChange() Dim source0 = " Public Class C Public Delegate Function F() As (Integer, Integer) End Class " Dim source1 = " Public Class C Public Delegate Function F() As (Integer, Boolean) End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of SourceNamedTypeSymbol)("C.F") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Tuple delegate defines a type. We should be able to match old and new types by name. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceNamedTypeSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.F", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleDelegate_NameChange() Dim source0 = " Public Class C Public Delegate Function F() As (x as Integer, y as Integer) End Class " Dim source1 = " Public Class C Public Delegate Function F() As (x as Integer, z as Integer) End Class" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of SourceNamedTypeSymbol)("C.F") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceNamedTypeSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.F", otherSymbol.ToTestDisplayString()) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Roslyn.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports System.Threading.Tasks Imports System.Threading Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SymbolMatcherTests Inherits EditAndContinueTestBase <Fact> Public Sub ConcurrentAccess() Dim source = " Class A Dim F As B Property P As D Sub M(a As A, b As B, s As S, i As I) : End Sub Delegate Sub D(s As S) Class B : End Class Structure S : End Structure Interface I : End Interface End Class Class B Function M(Of T, U)() As A Return Nothing End Function Event E As D Delegate Sub D(s As S) Structure S : End Structure Interface I : End Interface End Class" Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim builder = New List(Of Symbol)() Dim type = compilation1.GetMember(Of NamedTypeSymbol)("A") builder.Add(type) builder.AddRange(type.GetMembers()) type = compilation1.GetMember(Of NamedTypeSymbol)("B") builder.Add(type) builder.AddRange(type.GetMembers()) Dim members = builder.ToImmutableArray() Assert.True(members.Length > 10) For i = 0 To 10 - 1 Dim matcher = CreateMatcher(compilation1, compilation0) Dim tasks(10) As Task For j = 0 To tasks.Length - 1 Dim startAt As Integer = i + j + 1 tasks(j) = Task.Run(Sub() MatchAll(matcher, members, startAt) Thread.Sleep(10) End Sub) Next Task.WaitAll(tasks) Next End Sub Private Shared Sub MatchAll(matcher As VisualBasicSymbolMatcher, members As ImmutableArray(Of Symbol), startAt As Integer) Dim n As Integer = members.Length For i = 0 To n - 1 Dim member = members((i + startAt) Mod n) Dim other = matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IDefinition)) Assert.NotNull(other) Next End Sub <Fact> Public Sub TypeArguments() Dim source = " Class A(Of T) Class B(Of U) Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of Object).S) As A(Of V) Return Nothing End Function Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of V).S) As A(Of V) Return Nothing End Function End Class Structure S End Structure End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim matcher = CreateMatcher(compilation1, compilation0) Dim members = compilation1.GetMember(Of NamedTypeSymbol)("A.B").GetMembers("M") Assert.Equal(members.Length, 2) For Each member In members Dim other = matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IMethodDefinition)) Assert.NotNull(other) Next End Sub <Fact> Public Sub Constraints() Dim source = " Interface I(Of T AS I(Of T)) End Interface Class C Shared Sub M(Of T As I(Of T))(o As I(Of T)) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source) Dim matcher = CreateMatcher(compilation1, compilation0) Dim member = compilation1.GetMember(Of MethodSymbol)("C.M") Dim other = matcher.MapDefinition(member.GetCciAdapter()) Assert.NotNull(other) End Sub <Fact> Public Sub CustomModifiers() Dim ilSource = " .class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F(int32 modopt(object) p) { } } " Dim metadataRef = CompileIL(ilSource) Dim source = " Class B Inherits A Public Overrides Function F(p As Integer) As Object() Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, references:={metadataRef}) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim member1 = compilation1.GetMember(Of MethodSymbol)("B.F") Assert.Equal(DirectCast(member1.ReturnType, ArrayTypeSymbol).CustomModifiers.Length, 1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim other = DirectCast(matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) Assert.Equal(DirectCast(other.ReturnType, ArrayTypeSymbol).CustomModifiers.Length, 1) End Sub <Fact> Public Sub VaryingCompilationReferences() Dim libSource = " Public Class D End Class " Dim source = " Public Class C Public Sub F(a As D) End Sub End Class " Dim lib0 = CreateCompilationWithMscorlib40({libSource}, options:=TestOptions.DebugDll, assemblyName:="Lib") Dim lib1 = CreateCompilationWithMscorlib40({libSource}, options:=TestOptions.DebugDll, assemblyName:="Lib") Dim compilation0 = CreateCompilationWithMscorlib40({source}, {lib0.ToMetadataReference()}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source).WithReferences(MscorlibRef, lib1.ToMetadataReference()) Dim matcher = CreateMatcher(compilation1, compilation0) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim mf1 = matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol() Assert.Equal(f0, mf1) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub PreviousType_ArrayType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As Integer = 0 End Sub Class D : End Class End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x() As D = Nothing End Sub Class D : End Class End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim elementType = compilation1.GetMember(Of TypeSymbol)("C.D") Dim member = compilation1.CreateArrayTypeSymbol(elementType) Dim other = matcher.MapReference(member.GetCciAdapter()) Assert.NotNull(other) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub NoPreviousType_ArrayType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As Integer = 0 End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x() As D = Nothing End Sub Class D : End Class End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim elementType = compilation1.GetMember(Of TypeSymbol)("C.D") Dim member = compilation1.CreateArrayTypeSymbol(elementType) Dim other = matcher.MapReference(member.GetCciAdapter()) ' For a newly added type, there is no match in the previous generation. Assert.Null(other) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub NoPreviousType_GenericType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Class C Shared Sub M() Dim x As Integer = 0 End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Class C Shared Sub M() Dim x As List(Of D) = Nothing End Sub Class D : End Class Dim y As List(Of D) End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim member = compilation1.GetMember(Of FieldSymbol)("C.y") Dim other = matcher.MapReference(DirectCast(member.Type.GetCciAdapter(), Cci.ITypeReference)) ' For a newly added type, there is no match in the previous generation. Assert.Null(other) End Sub <Fact> Public Sub HoistedAnonymousTypes() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = New With { .A = 1 } Dim x2 = New With { .B = 1 } Dim y = New Func(Of Integer)(Function() x1.A + x2.B) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = New With { .A = 1 } Dim x2 = New With { .C = 1 } Dim y = New Func(Of Integer)(Function() x1.A + x2.C) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousType_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("B", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal(2, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single() Assert.Equal("_Closure$__1-0", displayClass.Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClass.GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub HoistedAnonymousTypes_Complex() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = { New With { .A = New With { .X = 1 } } } Dim x2 = { New With { .A = New With { .Y = 1 } } } Dim y = New Func(Of Integer)(Function() x1(0).A.X + x2(0).A.Y) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = { New With { .A = New With { .X = 1 } } } Dim x2 = { New With { .A = New With { .Z = 1 } } } Dim y = New Func(Of Integer)(Function() x1(0).A.X + x2(0).A.Z) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousType_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("X", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_2", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("Y", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal(3, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single() Assert.Equal("_Closure$__1-0", displayClass.Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClass.GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub HoistedAnonymousDelegate() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = Function(a As Integer) 1 Dim x2 = Function(b As Integer) 1 Dim y = New Func(Of Integer)(Function() x1(1) + x2(1)) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = Function(a As Integer) 1 Dim x2 = Function(c As Integer) 1 Dim y = New Func(Of Integer)(Function() x1(1) + x2(1)) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousDelegate_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create( New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True), New AnonymousTypeKeyField(AnonymousTypeDescriptor.FunctionReturnParameterName, isKey:=False, ignoreCase:=True)), isDelegate:=True)).Name) Assert.Equal("VB$AnonymousDelegate_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create( New AnonymousTypeKeyField("B", isKey:=False, ignoreCase:=True), New AnonymousTypeKeyField(AnonymousTypeDescriptor.FunctionReturnParameterName, isKey:=False, ignoreCase:=True)), isDelegate:=True)).Name) Assert.Equal(2, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClasses = peAssemblyBuilder.GetSynthesizedTypes(c).ToArray() Assert.Equal("_Closure$__", displayClasses(0).Name) Assert.Equal("_Closure$__1-0", displayClasses(1).Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClasses(1).GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub Method_RenameParameter() Dim source0 = " Class C Public Function X(a As Integer) As Integer Return a End Function End Class " Dim source1 = " Class C Public Function X(b As Integer) As Integer Return b End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) Assert.NotNull(other) End Sub <Fact> Public Sub TupleField_TypeChange() Dim source0 = " Class C { Public x As (a As Integer, b As Integer) }" Dim source1 = " Class C { Public x As (a As Integer, b As Boolean) }" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("C.x") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleField_NameChange() Dim source0 = " Class C { Public x As (a As Integer, b As Integer) }" Dim source1 = " Class C { Public x As (a As Integer, c As Integer) }" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("C.x") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceFieldSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.x As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleMethod_TypeToNoTupleChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As Integer() Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types should not match: one is tuple and another is not. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_TypeFromNoTupleChange() Dim source0 = " Class C Public Function X() As Integer() Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, b As Boolean) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types should not match: one is tuple and another is not. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_TypeChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, b As Boolean) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_NameChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, c As Integer) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceMemberMethodSymbol) Assert.NotNull(otherSymbol) Assert.Equal("Function C.X() As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleProperty_TypeChange() Dim source0 = " Class C Public ReadOnly Property X As (a As Integer, b As Integer) Get Return Nothing End Get End Property End Class " Dim source1 = " Class C Public ReadOnly Property X As (a As Integer, b As Boolean) Get Return Nothing End Get End Property End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of PropertySymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleProperty_NameChange() Dim source0 = " Class C Public ReadOnly Property X As (a As Integer, b As Integer) Get Return Nothing End Get End Property End Class " Dim source1 = " Class C Public ReadOnly Property X As (a As Integer, c As Integer) Get Return Nothing End Get End Property End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of PropertySymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourcePropertySymbol) Assert.NotNull(otherSymbol) Assert.Equal("ReadOnly Property C.X As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleStructField_TypeChange() Dim source0 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer) End Structure " Dim source1 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer, z As Integer) End Structure " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("Vector.Coordinates") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleStructField_NameChange() Dim source0 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer) End Structure " Dim source1 = " Public Structure Vector Public Coordinates As (x As Integer, z As Integer) End Structure " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("Vector.Coordinates") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceFieldSymbol) Assert.NotNull(otherSymbol) Assert.Equal("Vector.Coordinates As (x As System.Int32, y As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleDelegate_TypeChange() Dim source0 = " Public Class C Public Delegate Function F() As (Integer, Integer) End Class " Dim source1 = " Public Class C Public Delegate Function F() As (Integer, Boolean) End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of SourceNamedTypeSymbol)("C.F") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Tuple delegate defines a type. We should be able to match old and new types by name. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceNamedTypeSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.F", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleDelegate_NameChange() Dim source0 = " Public Class C Public Delegate Function F() As (x as Integer, y as Integer) End Class " Dim source1 = " Public Class C Public Delegate Function F() As (x as Integer, z as Integer) End Class" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing, Nothing) Dim member = compilation1.GetMember(Of SourceNamedTypeSymbol)("C.F") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceNamedTypeSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.F", otherSymbol.ToTestDisplayString()) End Sub End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/Syntax/SyntaxList.WithManyWeakChildren.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; namespace Microsoft.CodeAnalysis.Syntax { internal partial class SyntaxList { internal class WithManyWeakChildren : SyntaxList { private readonly ArrayElement<WeakReference<SyntaxNode>?>[] _children; // We calculate and store the positions of all children here. This way, getting the position // of all children is O(N) [N being the list size], otherwise it is O(N^2) because getting // the position of a child later requires traversing all previous siblings. private readonly int[] _childPositions; internal WithManyWeakChildren(InternalSyntax.SyntaxList.WithManyChildrenBase green, SyntaxNode parent, int position) : base(green, parent, position) { int count = green.SlotCount; _children = new ArrayElement<WeakReference<SyntaxNode>?>[count]; var childOffsets = new int[count]; int childPosition = position; var greenChildren = green.children; for (int i = 0; i < childOffsets.Length; ++i) { childOffsets[i] = childPosition; childPosition += greenChildren[i].Value.FullWidth; } _childPositions = childOffsets; } internal override int GetChildPosition(int index) { return _childPositions[index]; } internal override SyntaxNode GetNodeSlot(int index) { return GetWeakRedElement(ref _children[index].Value, index); } internal override SyntaxNode? GetCachedSlot(int index) { SyntaxNode? value = null; _children[index].Value?.TryGetTarget(out value); return value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; namespace Microsoft.CodeAnalysis.Syntax { internal partial class SyntaxList { internal class WithManyWeakChildren : SyntaxList { private readonly ArrayElement<WeakReference<SyntaxNode>?>[] _children; // We calculate and store the positions of all children here. This way, getting the position // of all children is O(N) [N being the list size], otherwise it is O(N^2) because getting // the position of a child later requires traversing all previous siblings. private readonly int[] _childPositions; internal WithManyWeakChildren(InternalSyntax.SyntaxList.WithManyChildrenBase green, SyntaxNode parent, int position) : base(green, parent, position) { int count = green.SlotCount; _children = new ArrayElement<WeakReference<SyntaxNode>?>[count]; var childOffsets = new int[count]; int childPosition = position; var greenChildren = green.children; for (int i = 0; i < childOffsets.Length; ++i) { childOffsets[i] = childPosition; childPosition += greenChildren[i].Value.FullWidth; } _childPositions = childOffsets; } internal override int GetChildPosition(int index) { return _childPositions[index]; } internal override SyntaxNode GetNodeSlot(int index) { return GetWeakRedElement(ref _children[index].Value, index); } internal override SyntaxNode? GetCachedSlot(int index) { SyntaxNode? value = null; _children[index].Value?.TryGetTarget(out value); return value; } } } }
-1