BindingCollectionInitializerTests.vb 74.5 KB
Newer Older
F
Fredric Silberberg 已提交
1
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

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 BindingCollectionInitializerTests
        Inherits BasicTestBase

        <Fact()>
B
beep boop 已提交
17
        Public Sub CollectionInitializerList()
P
Pilchie 已提交
18 19 20 21 22 23 24 25 26 27
            Dim source =
<compilation name="CollectionInitializerList">
    <file name="a.vb">
Option Strict On

Imports System
Imports System.Collections.Generic

Class C1
    Public Shared Sub Main()
28
        Dim c As New List(Of String) From {"Hello World!"}    'BIND:"New List(Of String) From {"Hello World!"}"    
P
Pilchie 已提交
29 30 31 32 33 34 35
        Console.WriteLine(c(0))
    End Sub
End Class        
    </file>
</compilation>

            CompileAndVerify(source, "Hello World!")
36 37 38

            Dim expectedOperationTree = <![CDATA[
IObjectCreationExpression (Constructor: Sub System.Collections.Generic.List(Of System.String)..ctor()) (OperationKind.ObjectCreationExpression, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'New List(Of ... lo World!"}')
39
  Arguments(0)
40
  Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'From {"Hello World!"}')
41 42 43 44
      Initializers(1):
          ICollectionElementInitializerExpression (AddMethod: Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '"Hello World!"')
            Arguments(1):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "Hello World!") (Syntax: '"Hello World!"')
45 46 47 48 49
]]>.Value

            Dim expectedDiagnostics = String.Empty

            VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
50 51 52
        End Sub

        <Fact()>
B
beep boop 已提交
53
        Public Sub CollectionInitializerListEachElementAsCollectionInitializer()
P
Pilchie 已提交
54 55 56 57 58 59 60 61 62 63
            Dim source =
<compilation name="CollectionInitializerListEachElementAsCollectionInitializer">
    <file name="a.vb">
Option Strict On

Imports System
Imports System.Collections.Generic

Class C1
    Public Shared Sub Main()
64
        Dim c As New List(Of String) From {{"Hello"}, {" "}, {"World!"}}'BIND:"New List(Of String) From {{"Hello"}, {" "}, {"World!"}}"
P
Pilchie 已提交
65 66 67 68 69 70 71 72 73 74

        For each element in c
            Console.Write(element)
        next element
    End Sub
End Class        
    </file>
</compilation>

            CompileAndVerify(source, "Hello World!")
75 76 77

            Dim expectedOperationTree = <![CDATA[
IObjectCreationExpression (Constructor: Sub System.Collections.Generic.List(Of System.String)..ctor()) (OperationKind.ObjectCreationExpression, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'New List(Of ... {"World!"}}')
78
  Arguments(0)
79
  Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'From {{"Hel ... {"World!"}}')
80 81 82 83 84 85 86 87 88 89
      Initializers(3):
          ICollectionElementInitializerExpression (AddMethod: Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '{"Hello"}')
            Arguments(1):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "Hello") (Syntax: '"Hello"')
          ICollectionElementInitializerExpression (AddMethod: Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '{" "}')
            Arguments(1):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: " ") (Syntax: '" "')
          ICollectionElementInitializerExpression (AddMethod: Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '{"World!"}')
            Arguments(1):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "World!") (Syntax: '"World!"')
90 91 92 93 94
]]>.Value

            Dim expectedDiagnostics = String.Empty

            VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
95 96 97
        End Sub

        <Fact()>
B
beep boop 已提交
98
        Public Sub CollectionInitializerDictionary()
P
Pilchie 已提交
99 100 101 102 103 104 105 106 107 108
            Dim source =
<compilation name="CollectionInitializerDictionary">
    <file name="a.vb">
Option Strict On

Imports System
Imports System.Collections.Generic

Class C1
    Public Shared Sub Main()
109
        Dim c As New Dictionary(Of String, Integer) From {{"Hello", 23}, {"World", 42}}'BIND:"New Dictionary(Of String, Integer) From {{"Hello", 23}, {"World", 42}}"
P
Pilchie 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123

        For Each keyValue In c
            Console.WriteLine(keyValue.Key + " " + keyValue.Value.ToString)
        Next

    End Sub
End Class        
    </file>
</compilation>

            CompileAndVerify(source, expectedOutput:=<![CDATA[
Hello 23
World 42
]]>)
124 125 126

            Dim expectedOperationTree = <![CDATA[
IObjectCreationExpression (Constructor: Sub System.Collections.Generic.Dictionary(Of System.String, System.Int32)..ctor()) (OperationKind.ObjectCreationExpression, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32)) (Syntax: 'New Diction ... orld", 42}}')
127
  Arguments(0)
128
  Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32)) (Syntax: 'From {{"Hel ... orld", 42}}')
129 130 131 132
      Initializers(2):
          ICollectionElementInitializerExpression (AddMethod: Sub System.Collections.Generic.Dictionary(Of System.String, System.Int32).Add(key As System.String, value As System.Int32)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '{"Hello", 23}')
            Arguments(2):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "Hello") (Syntax: '"Hello"')
133
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 23) (Syntax: '23')
134 135 136
          ICollectionElementInitializerExpression (AddMethod: Sub System.Collections.Generic.Dictionary(Of System.String, System.Int32).Add(key As System.String, value As System.Int32)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '{"World", 42}')
            Arguments(2):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "World") (Syntax: '"World"')
137
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 42) (Syntax: '42')
138 139 140 141 142
]]>.Value

            Dim expectedDiagnostics = String.Empty

            VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
143 144 145
        End Sub

        <Fact()>
B
beep boop 已提交
146
        Public Sub CollectionInitializerCustomCollection()
P
Pilchie 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
            Dim source =
<compilation name="CollectionInitializerCustomCollection">
    <file name="a.vb">
Option Strict On

Imports System
Imports System.Collections.Generic

Class Custom
    Private list As New List(Of String)()

    Public Function GetEnumerator() As CustomEnumerator
        Return New CustomEnumerator(list)
    End Function

    Public Sub add(p As String)
        list.Add(p)
    End Sub

    Public Class CustomEnumerator
        Private list As list(Of String)
        Private index As Integer = -1

        Public Sub New(list As List(Of String))
            Me.list = list
        End Sub

        Public Function MoveNext() As Boolean
            If Me.index &lt; Me.list.Count - 1 Then
                index = index + 1
                Return True
            End If

            Return False
        End function

        Public ReadOnly Property Current As String
            Get
                Return Me.list(index)
            End Get
        End Property
    End Class
End Class

    Class C1
        Public Shared Sub Main()
193
            Dim c as Custom = New Custom() From {"Hello", " ", "World"}'BIND:"New Custom() From {"Hello", " ", "World"}"
P
Pilchie 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
            Output(c)
        End Sub

        Public Shared Sub Output(c as custom)
            For Each value In c
                Console.Write(value)
            Next
        End Sub
    End Class
    </file>
</compilation>

            CompileAndVerify(source, expectedOutput:=<![CDATA[
Hello World
]]>).VerifyIL("C1.Main", <![CDATA[
{
  // Code size       44 (0x2c)
  .maxstack  3
  IL_0000:  newobj     "Sub Custom..ctor()"
  IL_0005:  dup
  IL_0006:  ldstr      "Hello"
  IL_000b:  callvirt   "Sub Custom.add(String)"
  IL_0010:  dup
  IL_0011:  ldstr      " "
  IL_0016:  callvirt   "Sub Custom.add(String)"
  IL_001b:  dup
  IL_001c:  ldstr      "World"
  IL_0021:  callvirt   "Sub Custom.add(String)"
  IL_0026:  call       "Sub C1.Output(Custom)"
  IL_002b:  ret
}
]]>.Value)
226 227 228

            Dim expectedOperationTree = <![CDATA[
IObjectCreationExpression (Constructor: Sub Custom..ctor()) (OperationKind.ObjectCreationExpression, Type: Custom) (Syntax: 'New Custom( ... ", "World"}')
229
  Arguments(0)
230
  Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: Custom) (Syntax: 'From {"Hell ... ", "World"}')
231 232 233 234 235 236 237 238 239 240
      Initializers(3):
          ICollectionElementInitializerExpression (AddMethod: Sub Custom.add(p As System.String)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '"Hello"')
            Arguments(1):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "Hello") (Syntax: '"Hello"')
          ICollectionElementInitializerExpression (AddMethod: Sub Custom.add(p As System.String)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '" "')
            Arguments(1):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: " ") (Syntax: '" "')
          ICollectionElementInitializerExpression (AddMethod: Sub Custom.add(p As System.String)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '"World"')
            Arguments(1):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "World") (Syntax: '"World"')
241 242 243 244 245
]]>.Value

            Dim expectedDiagnostics = String.Empty

            VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
246 247 248
        End Sub

        <Fact()>
B
beep boop 已提交
249
        Public Sub CollectionInitializerEmptyInitializers()
250
            Dim source = <![CDATA[
P
Pilchie 已提交
251 252 253 254 255 256 257 258 259 260
Option Strict On

Imports System.Collections.Generic

Class C2
End Class

Class C1
    Public Shared Sub Main()
        ' ok
261
        Dim a As New List(Of Integer) From {}
P
Pilchie 已提交
262 263

        ' not ok
264
        Dim b As New List(Of Integer) From {{}}'BIND:"New List(Of Integer) From {{}}"
P
Pilchie 已提交
265
    End Sub
266
End Class]]>.Value
P
Pilchie 已提交
267

268 269
            Dim expectedOperationTree = <![CDATA[
IObjectCreationExpression (Constructor: Sub System.Collections.Generic.List(Of System.Int32)..ctor()) (OperationKind.ObjectCreationExpression, Type: System.Collections.Generic.List(Of System.Int32), IsInvalid) (Syntax: 'New List(Of ... ) From {{}}')
270
  Arguments(0)
271
  Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: System.Collections.Generic.List(Of System.Int32), IsInvalid) (Syntax: 'From {{}}')
272 273 274
      Initializers(1):
          IInvalidExpression (OperationKind.InvalidExpression, Type: ?, IsInvalid) (Syntax: '{}')
            Children(0)
275 276 277
]]>.Value

            Dim expectedDiagnostics = <![CDATA[
P
Pilchie 已提交
278
BC36721: An aggregate collection initializer entry must contain at least one element.
279 280 281 282 283
        Dim b As New List(Of Integer) From {{}}'BIND:"New List(Of Integer) From {{}}"
                                            ~~
]]>.Value

            VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
284 285 286
        End Sub

        <Fact()>
B
beep boop 已提交
287
        Public Sub CollectionInitializerNotACollection()
288
            Dim source = <![CDATA[
P
Pilchie 已提交
289 290 291 292 293 294 295
Option Strict On

Imports System
Imports System.Collections.Generic

Class C1
    Public Shared Sub Main()
296
        Dim c As New C1() From {"Hello World!"}'BIND:"New C1() From {"Hello World!"}"
P
Pilchie 已提交
297
    End Sub
298
End Class]]>.Value
P
Pilchie 已提交
299

300 301
            Dim expectedOperationTree = <![CDATA[
IObjectCreationExpression (Constructor: Sub C1..ctor()) (OperationKind.ObjectCreationExpression, Type: C1, IsInvalid) (Syntax: 'New C1() Fr ... lo World!"}')
302
  Arguments(0)
303
  Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: C1, IsInvalid) (Syntax: 'From {"Hello World!"}')
304 305 306 307
      Initializers(1):
          IInvalidExpression (OperationKind.InvalidExpression, Type: ?, IsInvalid) (Syntax: '"Hello World!"')
            Children(1):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "Hello World!", IsInvalid) (Syntax: '"Hello World!"')
308
]]>.Value
P
Pilchie 已提交
309

310
            Dim expectedDiagnostics = <![CDATA[
P
Pilchie 已提交
311
BC36718: Cannot initialize the type 'C1' with a collection initializer because it is not a collection type.
312
        Dim c As New C1() From {"Hello World!"}'BIND:"New C1() From {"Hello World!"}"
P
Pilchie 已提交
313
                          ~~~~~~~~~~~~~~~~~~~~~
314 315 316
]]>.Value

            VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
317 318 319
        End Sub

        <Fact()>
B
beep boop 已提交
320
        Public Sub CollectionInitializerCannotCombineBothInitializers()
321
            Dim source = <![CDATA[
P
Pilchie 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
Option Strict On

Imports System
Imports System.Collections

Class C2
    Implements ICollection

    Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo
    End Sub

    Public ReadOnly Property Count As Integer Implements ICollection.Count
        Get
            Return 0
        End Get
    End Property

    Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized
        Get
            Return False
        End Get
    End Property

    Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot
        Get
            Return Nothing
        End Get
    End Property

    Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
        Return Nothing
    End Function

355
    Public a As String
P
Pilchie 已提交
356

357
    Public Sub Add(p As String)
P
Pilchie 已提交
358 359 360 361
    End Sub
End Class

Class C1
362
    Public a As String
P
Pilchie 已提交
363

364
    Public Shared Sub Main()'BIND:"Public Shared Sub Main()"
365 366 367 368
        Dim a As New C2() With {.a = "goo"} From {"Hello World!"}
        Dim b As New C2() From {"Hello World!"} With {.a = "goo"}
        Dim c As C2 = New C2() From {"Hello World!"} With {.a = "goo"}
        Dim d As C2 = New C2() With {.a = "goo"} From {"Hello World!"} 
P
Pilchie 已提交
369
    End Sub
370 371
End Class]]>.Value

F
Fredric Silberberg 已提交
372
            Dim expectedOperationTree = <![CDATA[
373
IBlockStatement (6 statements, 4 locals) (OperationKind.BlockStatement, IsInvalid) (Syntax: 'Public Shar ... End Sub')
374 375 376 377
  Locals: Local_1: a As C2
    Local_2: b As C2
    Local_3: c As C2
    Local_4: d As C2
378
  IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Dim a As Ne ... .a = "goo"}')
379 380
    IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'a')
      Variables: Local_1: a As C2
381
      Initializer: IObjectCreationExpression (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreationExpression, Type: C2) (Syntax: 'New C2() Wi ... .a = "goo"}')
382
          Arguments(0)
383
          Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: C2) (Syntax: 'With {.a = "goo"}')
384
              Initializers(1):
385
                  ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.String) (Syntax: '.a = "goo"')
386
                    Left: IFieldReferenceExpression: C2.a As System.String (OperationKind.FieldReferenceExpression, Type: System.String) (Syntax: 'a')
387 388
                        Instance Receiver: IOperation:  (OperationKind.None) (Syntax: 'New C2() Wi ... .a = "goo"}')
                    Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "goo") (Syntax: '"goo"')
389 390 391 392
  IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Dim b As Ne ... lo World!"}')
    IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'b')
      Variables: Local_1: b As C2
      Initializer: IObjectCreationExpression (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreationExpression, Type: C2) (Syntax: 'New C2() Fr ... lo World!"}')
393
          Arguments(0)
394
          Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: C2) (Syntax: 'From {"Hello World!"}')
395 396 397 398
              Initializers(1):
                  ICollectionElementInitializerExpression (AddMethod: Sub C2.Add(p As System.String)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '"Hello World!"')
                    Arguments(1):
                        ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "Hello World!") (Syntax: '"Hello World!"')
399
  IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement, IsInvalid) (Syntax: 'Dim c As C2 ... lo World!"}')
400 401
    IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c')
      Variables: Local_1: c As C2
402
      Initializer: IObjectCreationExpression (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreationExpression, Type: C2, IsInvalid) (Syntax: 'New C2() Fr ... lo World!"}')
403
          Arguments(0)
404
          Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: C2, IsInvalid) (Syntax: 'From {"Hello World!"}')
405 406 407 408
              Initializers(1):
                  ICollectionElementInitializerExpression (AddMethod: Sub C2.Add(p As System.String)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void, IsInvalid) (Syntax: '"Hello World!"')
                    Arguments(1):
                        ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "Hello World!", IsInvalid) (Syntax: '"Hello World!"')
409
  IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement, IsInvalid) (Syntax: 'Dim d As C2 ... .a = "goo"}')
410 411
    IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'd')
      Variables: Local_1: d As C2
412
      Initializer: IObjectCreationExpression (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreationExpression, Type: C2, IsInvalid) (Syntax: 'New C2() Wi ... .a = "goo"}')
413
          Arguments(0)
414
          Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: C2, IsInvalid) (Syntax: 'With {.a = "goo"}')
415
              Initializers(1):
416
                  ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.String, IsInvalid) (Syntax: '.a = "goo"')
417
                    Left: IFieldReferenceExpression: C2.a As System.String (OperationKind.FieldReferenceExpression, Type: System.String, IsInvalid) (Syntax: 'a')
418 419
                        Instance Receiver: IOperation:  (OperationKind.None, IsInvalid) (Syntax: 'New C2() Wi ... .a = "goo"}')
                    Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "goo", IsInvalid) (Syntax: '"goo"')
420
  ILabeledStatement (Label: exit) (OperationKind.LabeledStatement) (Syntax: 'End Sub')
F
Fredric Silberberg 已提交
421
    Statement: null
422
  IReturnStatement (OperationKind.ReturnStatement) (Syntax: 'End Sub')
423
    ReturnedValue: null
424 425 426
]]>.Value

            Dim expectedDiagnostics = <![CDATA[
P
Pilchie 已提交
427
BC36720: An Object Initializer and a Collection Initializer cannot be combined in the same initialization.
428
        Dim a As New C2() With {.a = "goo"} From {"Hello World!"}
P
Pilchie 已提交
429 430
                                            ~~~~
BC36720: An Object Initializer and a Collection Initializer cannot be combined in the same initialization.
431
        Dim b As New C2() From {"Hello World!"} With {.a = "goo"}
P
Pilchie 已提交
432 433
                                                ~~~~
BC36720: An Object Initializer and a Collection Initializer cannot be combined in the same initialization.
434
        Dim c As C2 = New C2() From {"Hello World!"} With {.a = "goo"}
P
Pilchie 已提交
435 436
                               ~~~~~~~~~~~~~~~~~~~~~
BC36720: An Object Initializer and a Collection Initializer cannot be combined in the same initialization.
437
        Dim d As C2 = New C2() With {.a = "goo"} From {"Hello World!"} 
438 439 440 441
                               ~~~~~~~~~~~~~~~~~
]]>.Value

            VerifyOperationTreeAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
442 443 444
        End Sub

        <Fact()>
B
beep boop 已提交
445
        Public Sub CollectionInitializerNoAddMethod()
446
            Dim source = <![CDATA[
P
Pilchie 已提交
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
Option Strict On

Imports System
Imports System.Collections

Class C2
    Implements ICollection

    Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo
    End Sub

    Public ReadOnly Property Count As Integer Implements ICollection.Count
        Get
            Return 0
        End Get
    End Property

    Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized
        Get
            Return False
        End Get
    End Property

    Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot
        Get
            Return Nothing
        End Get
    End Property

    Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
        Return Nothing
    End Function
End Class

Class C3
482
    Inherits C2
P
Pilchie 已提交
483 484 485 486 487 488

    Protected Sub Add()
    End Sub
End Class

Class C4
489
    Inherits C2
P
Pilchie 已提交
490

491
    Public Property Add() As String
P
Pilchie 已提交
492 493 494
End Class

Class C5
495
    Inherits C2
P
Pilchie 已提交
496

497
    Public Add As String
P
Pilchie 已提交
498 499 500
End Class

Class C1
501
    Public a As String
P
Pilchie 已提交
502 503

    Public Shared Sub Main()
504
        Dim a As New C2() From {"Hello World!"}'BIND:"New C2() From {"Hello World!"}"
P
Pilchie 已提交
505 506 507 508
        Dim b As New C3() From {"Hello World!"}
        Dim c As New C4() From {"Hello World!"}
        Dim d As New C5() From {"Hello World!"}
    End Sub
509
End Class]]>.Value
P
Pilchie 已提交
510

511 512
            Dim expectedOperationTree = <![CDATA[
IObjectCreationExpression (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreationExpression, Type: C2, IsInvalid) (Syntax: 'New C2() Fr ... lo World!"}')
513
  Arguments(0)
514
  Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: C2, IsInvalid) (Syntax: 'From {"Hello World!"}')
515 516 517 518
      Initializers(1):
          IInvalidExpression (OperationKind.InvalidExpression, Type: ?, IsInvalid) (Syntax: '"Hello World!"')
            Children(1):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "Hello World!", IsInvalid) (Syntax: '"Hello World!"')
519 520 521
]]>.Value

            Dim expectedDiagnostics = <![CDATA[
P
Pilchie 已提交
522
BC36719: Cannot initialize the type 'C2' with a collection initializer because it does not have an accessible 'Add' method.
523
        Dim a As New C2() From {"Hello World!"}'BIND:"New C2() From {"Hello World!"}"
P
Pilchie 已提交
524 525 526 527 528 529 530 531 532
                          ~~~~~~~~~~~~~~~~~~~~~
BC36719: Cannot initialize the type 'C3' with a collection initializer because it does not have an accessible 'Add' method.
        Dim b As New C3() From {"Hello World!"}
                          ~~~~~~~~~~~~~~~~~~~~~
BC36719: Cannot initialize the type 'C4' with a collection initializer because it does not have an accessible 'Add' method.
        Dim c As New C4() From {"Hello World!"}
                          ~~~~~~~~~~~~~~~~~~~~~
BC36719: Cannot initialize the type 'C5' with a collection initializer because it does not have an accessible 'Add' method.
        Dim d As New C5() From {"Hello World!"}
533 534 535 536
                          ~~~~~~~~~~~~~~~~~~~~~
]]>.Value

            VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
537 538 539
        End Sub

        <Fact()>
B
beep boop 已提交
540
        Public Sub CollectionInitializerAddMethodIsFunction()
P
Pilchie 已提交
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
            Dim source =
    <compilation name="CollectionInitializerAddMethodIsFunction">
        <file name="a.vb">
Option Strict On

Imports System
Imports System.Collections

Public Class C1
    Implements ICollection

    Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo
    End Sub

    Public ReadOnly Property Count As Integer Implements ICollection.Count
        Get
            Return 0
        End Get
    End Property

    Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized
        Get
            Return False
        End Get
    End Property

    Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot
        Get
            Return Nothing
        End Get
    End Property

    Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
        Return Nothing
    End Function

    Public Function Add(p As Integer) As String
        Console.WriteLine("What's the point of returning something here?")
        return "Boo!"
    End Function
End Class

Class C2
    Public Shared Sub Main()
585
        Dim x As New C1() From {1}'BIND:"New C1() From {1}"
P
Pilchie 已提交
586 587 588 589 590 591 592 593
    End Sub
End Class
    </file>
    </compilation>

            CompileAndVerify(source, expectedOutput:=<![CDATA[
What's the point of returning something here?
 ]]>)
594 595 596

            Dim expectedOperationTree = <![CDATA[
IObjectCreationExpression (Constructor: Sub C1..ctor()) (OperationKind.ObjectCreationExpression, Type: C1) (Syntax: 'New C1() From {1}')
597
  Arguments(0)
598
  Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: C1) (Syntax: 'From {1}')
599 600 601
      Initializers(1):
          ICollectionElementInitializerExpression (AddMethod: Function C1.Add(p As System.Int32) As System.String) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.String) (Syntax: '1')
            Arguments(1):
602
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1')
603 604 605 606 607
]]>.Value

            Dim expectedDiagnostics = String.Empty

            VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
608 609 610
        End Sub

        <Fact()>
B
beep boop 已提交
611
        Public Sub CollectionInitializerOverloadResolutionErrors()
612
            Dim source = <![CDATA[
P
Pilchie 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
Option Strict On

Imports System
Imports System.Collections

Class C2
    Implements ICollection

    Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo
    End Sub

    Public ReadOnly Property Count As Integer Implements ICollection.Count
        Get
            Return 0
        End Get
    End Property

    Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized
        Get
            Return False
        End Get
    End Property

    Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot
        Get
            Return Nothing
        End Get
    End Property

    Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
        Return Nothing
    End Function

    Public Sub Add()
    End Sub

649
    Protected Sub Add(p As String)
P
Pilchie 已提交
650 651 652 653
    End Sub
End Class

Class C3
654 655
    Inherits C2

P
Pilchie 已提交
656
    ' first argument matches
657
    Public Overloads Sub Add(p As String, q As Integer)
P
Pilchie 已提交
658 659 660 661
    End Sub
End Class

Class C4
662 663
    Inherits C2

P
Pilchie 已提交
664
    ' first argument does not match -> multiple candidates
665
    Public Overloads Sub Add(p As Integer, q As String)
P
Pilchie 已提交
666 667 668 669
    End Sub
End Class

Class C5
670 671
    Inherits C2

P
Pilchie 已提交
672
    ' first argument does not match -> multiple candidates
673
    Public Overloads Sub Add(p As Byte)
P
Pilchie 已提交
674 675 676 677
    End Sub
End Class

Class C1
678
    Public a As String
P
Pilchie 已提交
679 680

    Public Shared Sub Main()
681
        Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"From {"Hello World!", "Errors will be shown for each initializer element"}"
P
Pilchie 已提交
682 683 684 685
        Dim b As New C3() From {"Hello World!"}
        Dim c As New C4() From {"Hello World!"}
        Dim d As New C5() From {300%}
    End Sub
686 687 688 689
End Class]]>.Value

            Dim expectedOperationTree = <![CDATA[
IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: C2, IsInvalid) (Syntax: 'From {"Hell ... r element"}')
690 691 692 693 694 695 696 697 698
  Initializers(2):
      IInvalidExpression (OperationKind.InvalidExpression, Type: System.Void, IsInvalid) (Syntax: '"Hello World!"')
        Children(2):
            IOperation:  (OperationKind.None, IsInvalid) (Syntax: '"Hello World!"')
            ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "Hello World!", IsInvalid) (Syntax: '"Hello World!"')
      IInvalidExpression (OperationKind.InvalidExpression, Type: System.Void, IsInvalid) (Syntax: '"Errors wil ... er element"')
        Children(2):
            IOperation:  (OperationKind.None, IsInvalid) (Syntax: '"Errors wil ... er element"')
            ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "Errors will be shown for each initializer element", IsInvalid) (Syntax: '"Errors wil ... er element"')
699 700 701
]]>.Value

            Dim expectedDiagnostics = <![CDATA[
P
Pilchie 已提交
702
BC30057: Too many arguments to 'Public Sub Add()'.
703
        Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"From {"Hello World!", "Errors will be shown for each initializer element"}"
P
Pilchie 已提交
704 705
                                ~~~~~~~~~~~~~~
BC30057: Too many arguments to 'Public Sub Add()'.
706
        Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"From {"Hello World!", "Errors will be shown for each initializer element"}"
P
Pilchie 已提交
707 708 709 710 711 712 713 714 715 716
                                                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30516: Overload resolution failed because no accessible 'Add' accepts this number of arguments.
        Dim b As New C3() From {"Hello World!"}
                                ~~~~~~~~~~~~~~
BC30516: Overload resolution failed because no accessible 'Add' accepts this number of arguments.
        Dim c As New C4() From {"Hello World!"}
                                ~~~~~~~~~~~~~~
BC30439: Constant expression not representable in type 'Byte'.
        Dim d As New C5() From {300%}
                                ~~~~
717 718 719
]]>.Value

            VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCollectionInitializerSyntax)(source, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
720 721 722
        End Sub

        <Fact()>
B
beep boop 已提交
723
        Public Sub CollectionInitializerWarningsWillBeKept()
724
            Dim source = <![CDATA[
P
Pilchie 已提交
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
Option Strict On

Imports System
Imports System.Collections

Class C2
    Implements ICollection

    Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo
    End Sub

    Public ReadOnly Property Count As Integer Implements ICollection.Count
        Get
            Return 0
        End Get
    End Property

    Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized
        Get
            Return False
        End Get
    End Property

    Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot
        Get
            Return Nothing
        End Get
    End Property

    Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
        Return Nothing
    End Function

758
    Public Shared Sub Add(p As String)
P
Pilchie 已提交
759 760 761 762
    End Sub
End Class

Class C1
763
    Public a As String
P
Pilchie 已提交
764 765

    Public Shared Sub Main()
766
        Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"New C2() From {"Hello World!", "Errors will be shown for each initializer element"}"
P
Pilchie 已提交
767
    End Sub
768 769 770 771
End Class]]>.Value

            Dim expectedOperationTree = <![CDATA[
IObjectCreationExpression (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreationExpression, Type: C2) (Syntax: 'New C2() Fr ... r element"}')
772
  Arguments(0)
773
  Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: C2) (Syntax: 'From {"Hell ... r element"}')
774 775 776 777 778 779 780
      Initializers(2):
          ICollectionElementInitializerExpression (AddMethod: Sub C2.Add(p As System.String)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '"Hello World!"')
            Arguments(1):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "Hello World!") (Syntax: '"Hello World!"')
          ICollectionElementInitializerExpression (AddMethod: Sub C2.Add(p As System.String)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '"Errors wil ... er element"')
            Arguments(1):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "Errors will be shown for each initializer element") (Syntax: '"Errors wil ... er element"')
781 782 783
]]>.Value

            Dim expectedDiagnostics = <![CDATA[
P
Pilchie 已提交
784
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
785
        Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"New C2() From {"Hello World!", "Errors will be shown for each initializer element"}"
P
Pilchie 已提交
786 787
                                ~~~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
788
        Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"New C2() From {"Hello World!", "Errors will be shown for each initializer element"}"
P
Pilchie 已提交
789
                                                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
790 791 792
]]>.Value

            VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
793 794 795
        End Sub

        <Fact()>
B
beep boop 已提交
796
        Public Sub CollectionInitializerExtensionMethodsAreSupported()
P
Pilchie 已提交
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
            Dim source =
    <compilation name="CollectionInitializerExtensionMethodsAreSupported">
        <file name="a.vb">
Option Strict On

Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices

Class C2
    Implements ICollection

    Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo
    End Sub

    Public ReadOnly Property Count As Integer Implements ICollection.Count
        Get
            Return 0
        End Get
    End Property

    Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized
        Get
            Return False
        End Get
    End Property

    Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot
        Get
            Return Nothing
        End Get
    End Property

    Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
        Return Nothing
    End Function
End Class

Class C1
    public a as string

    Public Shared Sub Main()
        ' extensions for custom type
        Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}

        ' extensions for predefined type
        Dim x0 As LinkedList(Of Integer) = New LinkedList(Of Integer) From {1, 2, 3}
    End Sub
End Class        

Module C2Extensions
    &lt;Extension()&gt;
    Public Sub Add(this as C2, p as string)
    End Sub

    &lt;Extension()&gt;
    Public Sub ADD(ByRef x As LinkedList(Of Integer), ByVal y As Integer)
        x.AddLast(y)
    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>

            Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source)
            AssertTheseDiagnostics(compilation, <expected>
                                                </expected>)
        End Sub

        <Fact()>
B
beep boop 已提交
876
        Public Sub CollectionInitializerExtensionMethodsAreSupportedForValueTypes()
P
Pilchie 已提交
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
            Dim source =
    <compilation name="CollectionInitializerExtensionMethodsAreSupportedForValueTypes">
        <file name="a.vb">
Option Strict On

Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices

Structure C2
    Implements ICollection

    Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo
    End Sub

    Public ReadOnly Property Count As Integer Implements ICollection.Count
        Get
            Return 0
        End Get
    End Property

    Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized
        Get
            Return False
        End Get
    End Property

    Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot
        Get
            Return Nothing
        End Get
    End Property

    Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
        Return Nothing
    End Function
End Structure

Class C1
    public a as string

    Public Shared Sub Main()
        Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}
    End Sub
End Class        

Module C2Extensions
    &lt;Extension()&gt;
    Public Sub Add(this as C2, p as string)
    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>

            Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source)
            AssertTheseDiagnostics(compilation, <expected>
                                                </expected>)
        End Sub

        <Fact()>
B
beep boop 已提交
947
        Public Sub CollectionInitializerTypeConstraintsAreSupported()
P
Pilchie 已提交
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
            Dim source =
    <compilation name="CollectionInitializerTypeConstraintsAreSupported">
        <file name="a.vb">
Option Strict On

Imports System
Imports System.Collections
Imports System.Collections.Generic

Public Interface IAdd(Of T)
    Sub Add(p As T)
End Interface

Public Class C2
    Public Sub Add()
    End Sub
End Class

Class C3
    Implements IAdd(Of String), ICollection

    private mylist as new list(of String)()

    Public Sub New()
    End Sub

    Public Sub Add1(p As String) Implements IAdd(Of String).Add
        mylist.add(p)
    End Sub

    Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo
    End Sub

    Public ReadOnly Property Count As Integer Implements ICollection.Count
        Get
            Return 0
        End Get
    End Property

    Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized
        Get
            Return False
        End Get
    End Property

    Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot
        Get
            Return False
        End Get
    End Property

    Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
        Return mylist.getenumerator
    End Function
End Class

Class C1
    Public Shared Sub DoStuff(Of T As {IAdd(Of String), ICollection, New})()
        Dim a As New T() From {"Hello", " ", "World!"}

        for each str as string in a
            Console.Write(str)
        next str
    End Sub

    Public Shared Sub Main()
        DoStuff(Of C3)()
    End Sub
End Class 
    </file>
    </compilation>

            CompileAndVerify(source, "Hello World!")
        End Sub

        <Fact()>
B
beep boop 已提交
1024
        Public Sub CollectionInitializerTypeConstraintsAndAmbiguity()
1025
            Dim source = <![CDATA[
P
Pilchie 已提交
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
Option Strict On

Imports System
Imports System.Collections
Imports System.Collections.Generic

Public Interface IAdd(Of T)
    Sub Add(p As String)
End Interface

Class C1
    Public Shared Sub DoStuff(Of T As {IAdd(Of String), IAdd(Of Integer), ICollection, New})()
1038
        Dim a As New T() From {"Hello", " ", "World!"}'BIND:"New T() From {"Hello", " ", "World!"}"
P
Pilchie 已提交
1039

1040
        For Each str As String In a
P
Pilchie 已提交
1041
            Console.Write(str)
1042
        Next str
P
Pilchie 已提交
1043 1044 1045 1046
    End Sub

    Public Shared Sub Main()
    End Sub
1047
End Class]]>.Value
P
Pilchie 已提交
1048

1049 1050 1051 1052 1053
            Dim expectedOperationTree = <![CDATA[
ITypeParameterObjectCreationExpression (OperationKind.TypeParameterObjectCreationExpression, Type: T, IsInvalid) (Syntax: 'New T() Fro ... , "World!"}')
]]>.Value

            Dim expectedDiagnostics = <![CDATA[
1054
BC30521: Overload resolution failed because no accessible 'Add' is most specific for these arguments:
1055 1056
    'Sub IAdd(Of String).Add(p As String)': Not most specific.
    'Sub IAdd(Of Integer).Add(p As String)': Not most specific.
1057
        Dim a As New T() From {"Hello", " ", "World!"}'BIND:"New T() From {"Hello", " ", "World!"}"
1058 1059
                               ~~~~~~~
BC30521: Overload resolution failed because no accessible 'Add' is most specific for these arguments:
1060 1061
    'Sub IAdd(Of String).Add(p As String)': Not most specific.
    'Sub IAdd(Of Integer).Add(p As String)': Not most specific.
1062
        Dim a As New T() From {"Hello", " ", "World!"}'BIND:"New T() From {"Hello", " ", "World!"}"
1063 1064
                                        ~~~
BC30521: Overload resolution failed because no accessible 'Add' is most specific for these arguments:
1065 1066
    'Sub IAdd(Of String).Add(p As String)': Not most specific.
    'Sub IAdd(Of Integer).Add(p As String)': Not most specific.
1067
        Dim a As New T() From {"Hello", " ", "World!"}'BIND:"New T() From {"Hello", " ", "World!"}"
1068
                                             ~~~~~~~~
1069 1070 1071
]]>.Value

            VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
1072 1073
        End Sub

J
Jared Parsons 已提交
1074
        <WorkItem(529265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529265")>
P
Pilchie 已提交
1075
        <Fact()>
B
beep boop 已提交
1076
        Public Sub CollectionInitializerCollectionInitializerArityCheck()
1077
            Dim source = <![CDATA[
P
Pilchie 已提交
1078 1079 1080 1081 1082 1083 1084
Option Strict On

Imports System
Imports System.Collections.Generic

Class C1
    Public Shared Sub Main()
1085
        Dim x As New Dictionary(Of String, Integer) From {{1}}'BIND:"New Dictionary(Of String, Integer) From {{1}}"
P
Pilchie 已提交
1086
    End Sub
1087
End Class]]>.Value
P
Pilchie 已提交
1088

1089 1090
            Dim expectedOperationTree = <![CDATA[
IObjectCreationExpression (Constructor: Sub System.Collections.Generic.Dictionary(Of System.String, System.Int32)..ctor()) (OperationKind.ObjectCreationExpression, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32), IsInvalid) (Syntax: 'New Diction ...  From {{1}}')
1091
  Arguments(0)
1092
  Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32), IsInvalid) (Syntax: 'From {{1}}')
1093 1094 1095 1096
      Initializers(1):
          IInvalidExpression (OperationKind.InvalidExpression, Type: System.Void, IsInvalid) (Syntax: '{1}')
            Children(2):
                IOperation:  (OperationKind.None, IsInvalid) (Syntax: '{1}')
1097
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
1098 1099 1100
]]>.Value

            Dim expectedDiagnostics = <![CDATA[
P
Pilchie 已提交
1101
BC30455: Argument not specified for parameter 'value' of 'Public Overloads Sub Add(key As String, value As Integer)'.
1102
        Dim x As New Dictionary(Of String, Integer) From {{1}}'BIND:"New Dictionary(Of String, Integer) From {{1}}"
P
Pilchie 已提交
1103 1104
                                                          ~~~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'.
1105 1106 1107 1108 1109
        Dim x As New Dictionary(Of String, Integer) From {{1}}'BIND:"New Dictionary(Of String, Integer) From {{1}}"
                                                           ~
]]>.Value

            VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
1110 1111 1112
        End Sub

        <Fact()>
B
beep boop 已提交
1113
        Public Sub CollectionInitializerReferencingItself()
P
Pilchie 已提交
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
            Dim source =
<compilation name="CollectionInitializerReferencingItselfRefType">
    <file name="a.vb">
Option Strict On

Imports System
Imports System.Collections.Generic
Imports System.Collections

Interface IMissingStuff
    Sub Add(p As String)
    Function Item() As String
End Interface

Structure Custom
    Implements IMissingStuff, IEnumerable(Of String)

    Public Shared list As New List(Of String)()

    Public Sub Add(p As String) Implements IMissingStuff.Add
        list.Add(p)
    End Sub

    Public Function Item() As String Implements IMissingStuff.Item
        Return Nothing
    End Function

    Public Structure CustomEnumerator
        Implements IEnumerator(Of String)

        Private list As List(Of String)
        Private Shared index As Integer = -1

        Public Sub New(list As List(Of String))
            Me.list = list
        End Sub

        Public Function MoveNext() As Boolean
            If index &lt; Me.list.Count - 1 Then
                index = index + 1
            Return True
            End If

            Return False
        End function

        Public ReadOnly Property Current As String
            Get
                Return Me.list(index)
            End Get
        End Property

        Public ReadOnly Property Current1 As String Implements IEnumerator(Of String).Current
            Get
                Return Current
            End Get
        End Property

        Public ReadOnly Property Current2 As Object Implements IEnumerator.Current
            Get
                Return Current
            End Get
        End Property

        Public Function MoveNext1() As Boolean Implements IEnumerator.MoveNext
            Return MoveNext()
        End Function

        Public Sub Reset() Implements IEnumerator.Reset

        End Sub

        Public Sub Dispose() Implements IDisposable.Dispose

        End Sub
    end structure

    Public Function GetEnumerator1() As IEnumerator(Of String) Implements IEnumerable(Of String).GetEnumerator
        Return New CustomEnumerator(list)
    End Function

    Public Function GetEnumerator2() As IEnumerator Implements IEnumerable.GetEnumerator
        Return New CustomEnumerator(list)
    End Function
End Structure

Structure CustomNonEmpty
    Implements IMissingStuff, IEnumerable(Of String)

    Public MakeItNonEmpty as String

    Public Shared list As New List(Of String)()

    Public Sub Add(p As String) Implements IMissingStuff.Add
        list.Add(p)
    End Sub

    Public Function Item() As String Implements IMissingStuff.Item
        Return Nothing
    End Function

    Public Structure CustomEnumerator
        Implements IEnumerator(Of String)

        Private list As List(Of String)
        Private Shared index As Integer = -1

        Public Sub New(list As List(Of String))
            Me.list = list
        End Sub

        Public Function MoveNext() As Boolean
            If index &lt; Me.list.Count - 1 Then
                index = index + 1
            Return True
            End If

            Return False
        End function

        Public ReadOnly Property Current As String
            Get
                Return Me.list(index)
            End Get
        End Property

        Public ReadOnly Property Current1 As String Implements IEnumerator(Of String).Current
            Get
                Return Current
            End Get
        End Property

        Public ReadOnly Property Current2 As Object Implements IEnumerator.Current
            Get
                Return Current
            End Get
        End Property

        Public Function MoveNext1() As Boolean Implements IEnumerator.MoveNext
            Return MoveNext()
        End Function

        Public Sub Reset() Implements IEnumerator.Reset

        End Sub

        Public Sub Dispose() Implements IDisposable.Dispose

        End Sub
    end structure

    Public Function GetEnumerator1() As IEnumerator(Of String) Implements IEnumerable(Of String).GetEnumerator
        Return New CustomEnumerator(list)
    End Function

    Public Function GetEnumerator2() As IEnumerator Implements IEnumerable.GetEnumerator
        Return New CustomEnumerator(list)
    End Function
End Structure

Class CBase(Of T)
    Public Overridable Sub TypeParameterValueTypeAsClassConstraint(Of U As {T, IEnumerable, IMissingStuff})()
    End Sub
End Class

Class CDerived
    Inherits CBase(Of Custom)

    Public Overrides Sub TypeParameterValueTypeAsClassConstraint(Of U As {Custom, IEnumerable, IMissingStuff})()
        Dim m As New U From {"Hello World!", m.Item(0)}                                             ' temp used, m is uninitialized, show warning
        Dim n As U = New U() From {"Hello World!", n.Item(0)}                                       ' temp used, h is uninitialized, show warning
        Dim o, p As New U() From {o.Item(0), p.Item(0)}                                             ' temps used, show warnings (although o is initialized when initializing p)
    End Sub
End Class

        Class C1
            Public Sub TypeParameterNotDefined(Of T As {IEnumerable, IMissingStuff, New})()
                ' no warnings from type parameters as well
                Dim e As New T From {"Hello World!", e.Item(0)}                                     ' Receiver type unknown, no warning
                Dim f As T = New T() From {"Hello World!", f.Item(0)}                               ' Receiver type unknown, no warning
            End Sub

            Public Sub TypeParameterAsStructure(Of T As {Structure, IEnumerable, IMissingStuff})()
                ' no warnings from type parameters as well
                Dim g As New T From {"Hello World!", g.Item(0)}                                     ' temp used, g is uninitialized, show warning
                Dim h As T = New T() From {"Hello World!", h.Item(0)}                               ' temp used, h is uninitialized, show warning
                Dim i, j As New T() From {i.Item(0), j.Item(0)}                                     ' temps used, show warnings (although i is initialized when initializing j)
            End Sub

            Public Sub TypeParameterAsRefType(Of T As {List(Of String), new})()
                Dim k As New T From {"Hello World!", k.Item(0)}                                     ' temp used, k is uninitialized, show warning
                Dim l As T = New T() From {"Hello World!", l.Item(0)}                               ' temp used, l is uninitialized, show warning
            End Sub

            Public Shared Sub Main()
                Dim a As New Custom From {"Hello World!", a.Item(0)}                                ' empty, non trackable structure, no warning
                Dim b As Custom = New Custom() From {"Hello World!", b.Item(0)}                     ' empty, non trackable structure, no warning

                Dim q As New CustomNonEmpty From {"Hello World!", q.Item(0)}                        ' temp used, q is uninitialized, show warning
                Dim r As CustomNonEmpty = New CustomNonEmpty() From {"Hello World!", r.Item(0)}     ' temp used, r is uninitialized, show warning

                ' reference types are not ok, they are still Nothing
                Dim c As New List(Of String) From {"Hello World!", c.Item(0)}                       ' show warning
                Dim d As List(Of String) = New List(Of String)() From {"Hello World!", d.Item(0)}   ' show warning

                ' was already assigned, no warning again.
                c = New List(Of String)() From {"Hello World!", c.Item(0)}                          ' no warning
            End Sub
        End Class
    </file>
</compilation>

            Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source)
            AssertTheseDiagnostics(compilation, <expected>
BC42109: Variable 'm' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
        Dim m As New U From {"Hello World!", m.Item(0)}                                             ' temp used, m is uninitialized, show warning
                                             ~
BC42109: Variable 'n' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
        Dim n As U = New U() From {"Hello World!", n.Item(0)}                                       ' temp used, h is uninitialized, show warning
                                                   ~
BC42109: Variable 'o' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
        Dim o, p As New U() From {o.Item(0), p.Item(0)}                                             ' temps used, show warnings (although o is initialized when initializing p)
                                  ~
BC42109: Variable 'p' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
        Dim o, p As New U() From {o.Item(0), p.Item(0)}                                             ' temps used, show warnings (although o is initialized when initializing p)
                                             ~
BC42109: Variable 'g' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
                Dim g As New T From {"Hello World!", g.Item(0)}                                     ' temp used, g is uninitialized, show warning
                                                     ~
BC42109: Variable 'h' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
                Dim h As T = New T() From {"Hello World!", h.Item(0)}                               ' temp used, h is uninitialized, show warning
                                                           ~
BC42109: Variable 'i' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
                Dim i, j As New T() From {i.Item(0), j.Item(0)}                                     ' temps used, show warnings (although i is initialized when initializing j)
                                          ~
BC42109: Variable 'j' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
                Dim i, j As New T() From {i.Item(0), j.Item(0)}                                     ' temps used, show warnings (although i is initialized when initializing j)
                                                     ~
BC42104: Variable 'k' is used before it has been assigned a value. A null reference exception could result at runtime.
                Dim k As New T From {"Hello World!", k.Item(0)}                                     ' temp used, k is uninitialized, show warning
                                                     ~
BC42104: Variable 'l' is used before it has been assigned a value. A null reference exception could result at runtime.
                Dim l As T = New T() From {"Hello World!", l.Item(0)}                               ' temp used, l is uninitialized, show warning
                                                           ~
BC42109: Variable 'q' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
                Dim q As New CustomNonEmpty From {"Hello World!", q.Item(0)}                        ' temp used, q is uninitialized, show warning
                                                                  ~
BC42109: Variable 'r' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
                Dim r As CustomNonEmpty = New CustomNonEmpty() From {"Hello World!", r.Item(0)}     ' temp used, r is uninitialized, show warning
                                                                                     ~
BC42104: Variable 'c' is used before it has been assigned a value. A null reference exception could result at runtime.
                Dim c As New List(Of String) From {"Hello World!", c.Item(0)}                       ' show warning
                                                                   ~
BC42104: Variable 'd' is used before it has been assigned a value. A null reference exception could result at runtime.
                Dim d As List(Of String) = New List(Of String)() From {"Hello World!", d.Item(0)}   ' show warning
                                                                                       ~
                                           </expected>)
        End Sub

        <Fact()>
B
beep boop 已提交
1374
        Public Sub CollectionInitializerReferencingItself_2()
1375
            Dim source = <![CDATA[
P
Pilchie 已提交
1376 1377 1378 1379 1380
Imports System
Imports System.Collections.Generic

Module Program
    Sub Main(args As String())
1381
        Dim x, y As New List(Of String)() From {"1", x.Item(0)}'BIND:"New List(Of String)() From {"1", x.Item(0)}"
P
Pilchie 已提交
1382 1383
        Dim z As New List(Of String)() From {"1", z.Item(0)}
    End Sub
1384 1385 1386 1387
End Module]]>.Value

            Dim expectedOperationTree = <![CDATA[
IObjectCreationExpression (Constructor: Sub System.Collections.Generic.List(Of System.String)..ctor()) (OperationKind.ObjectCreationExpression, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'New List(Of ...  x.Item(0)}')
1388
  Arguments(0)
1389
  Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'From {"1", x.Item(0)}')
1390 1391 1392 1393 1394 1395 1396
      Initializers(2):
          ICollectionElementInitializerExpression (AddMethod: Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '"1"')
            Arguments(1):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "1") (Syntax: '"1"')
          ICollectionElementInitializerExpression (AddMethod: Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: 'x.Item(0)')
            Arguments(1):
                IPropertyReferenceExpression: Property System.Collections.Generic.List(Of System.String).Item(index As System.Int32) As System.String (OperationKind.PropertyReferenceExpression, Type: System.String) (Syntax: 'x.Item(0)')
1397
                  Instance Receiver: ILocalReferenceExpression: x (OperationKind.LocalReferenceExpression, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'x')
1398 1399
                  Arguments(1):
                      IArgument (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument) (Syntax: '0')
1400
                        ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0) (Syntax: '0')
1401 1402
                        InConversion: null
                        OutConversion: null
1403 1404 1405
]]>.Value

            Dim expectedDiagnostics = <![CDATA[
P
Pilchie 已提交
1406
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
1407
        Dim x, y As New List(Of String)() From {"1", x.Item(0)}'BIND:"New List(Of String)() From {"1", x.Item(0)}"
P
Pilchie 已提交
1408 1409 1410
                                                     ~
BC42104: Variable 'z' is used before it has been assigned a value. A null reference exception could result at runtime.
        Dim z As New List(Of String)() From {"1", z.Item(0)}
1411 1412 1413 1414
                                                  ~
]]>.Value

            VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
1415 1416 1417
        End Sub

        <Fact()>
B
beep boop 已提交
1418
        Public Sub CollectionInitializerCustomCollectionOptionalParameter()
P
Pilchie 已提交
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
            Dim source =
<compilation name="CollectionInitializerCustomCollection">
    <file name="a.vb">
Option Strict On

Imports System
Imports System.Collections.Generic

Class Custom
    Private list As New List(Of String)()

    Public Function GetEnumerator() As CustomEnumerator
        Return New CustomEnumerator(list)
    End Function

    Public Sub add(p As String, optional p2 as String = " ")
        list.Add(p)
        list.Add(p2)
    End Sub

    Public Class CustomEnumerator
        Private list As list(Of String)
        Private index As Integer = -1

        Public Sub New(list As List(Of String))
            Me.list = list
        End Sub

        Public Function MoveNext() As Boolean
            If Me.index &lt; Me.list.Count - 1 Then
                index = index + 1
                Return True
            End If

            Return False
        End function

        Public ReadOnly Property Current As String
            Get
                Return Me.list(index)
            End Get
        End Property
    End Class
End Class

    Class C1
        Public Shared Sub Main()
1466
            Dim c as Custom = New Custom() From {"Hello", {"World", "!"}}'BIND:"New Custom() From {"Hello", {"World", "!"}}"
P
Pilchie 已提交
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
            Output(c)
        End Sub

        Public Shared Sub Output(c as custom)
            For Each value In c
                Console.Write(value)
            Next
        End Sub
    End Class
    </file>
</compilation>

            CompileAndVerify(source, expectedOutput:=<![CDATA[
Hello World!
]]>)
1482 1483 1484

            Dim expectedOperationTree = <![CDATA[
IObjectCreationExpression (Constructor: Sub Custom..ctor()) (OperationKind.ObjectCreationExpression, Type: Custom) (Syntax: 'New Custom( ... rld", "!"}}')
1485
  Arguments(0)
1486
  Initializer: IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: Custom) (Syntax: 'From {"Hell ... rld", "!"}}')
1487 1488 1489 1490 1491 1492 1493 1494 1495
      Initializers(2):
          ICollectionElementInitializerExpression (AddMethod: Sub Custom.add(p As System.String, [p2 As System.String = " "])) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '"Hello"')
            Arguments(2):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "Hello") (Syntax: '"Hello"')
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: " ") (Syntax: '"Hello"')
          ICollectionElementInitializerExpression (AddMethod: Sub Custom.add(p As System.String, [p2 As System.String = " "])) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '{"World", "!"}')
            Arguments(2):
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "World") (Syntax: '"World"')
                ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "!") (Syntax: '"!"')
1496 1497 1498 1499 1500
]]>.Value

            Dim expectedDiagnostics = String.Empty

            VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics)
P
Pilchie 已提交
1501 1502 1503
        End Sub

        <Fact()>
B
beep boop 已提交
1504
        Public Sub CollectionInitializerCustomCollectionParamArray()
P
Pilchie 已提交
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
            Dim source =
<compilation name="CollectionInitializerCustomCollection">
    <file name="a.vb">
Option Strict On

Imports System
Imports System.Collections.Generic

Class Custom
    Private list As New List(Of String)()

    Public Function GetEnumerator() As CustomEnumerator
        Return New CustomEnumerator(list)
    End Function

    Public Sub add(paramarray p() As String)
        list.AddRange(p)
    End Sub

    Public Class CustomEnumerator
        Private list As list(Of String)
        Private index As Integer = -1

        Public Sub New(list As List(Of String))
            Me.list = list
        End Sub

        Public Function MoveNext() As Boolean
            If Me.index &lt; Me.list.Count - 1 Then
                index = index + 1
                Return True
            End If

            Return False
        End function

        Public ReadOnly Property Current As String
            Get
                Return Me.list(index)
            End Get
        End Property
    End Class
End Class

    Class C1
        Public Shared Sub Main()
            Dim c as Custom = New Custom() From {"Hello", {" ", "World"}, ({"!", "!", "!"})} 
            Output(c)
        End Sub

        Public Shared Sub Output(c as custom)
            For Each value In c
                Console.Write(value)
            Next
        End Sub
    End Class
    </file>
</compilation>

            CompileAndVerify(source, expectedOutput:=<![CDATA[
Hello World!!!
]]>)
        End Sub

J
Jared Parsons 已提交
1569
        <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")>
P
Pilchie 已提交
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
        Public Sub GetCollectionInitializerSymbolInfo_01()
            Dim compilation = CreateCompilationWithMscorlib(
<compilation>
    <file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
 
class X 
    Inherits List(Of Integer)

    Sub Add(x As Integer)
    End Sub

    Sub Add(x As String)
    End Sub
 
    Shared Sub Main()
        Dim z = new X() From { String.Empty, 'BIND1:"String.Empty"
                                12}          'BIND2:"12"
    End Sub
End Class
    ]]></file>
</compilation>)

            Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
            Dim semanticInfo As SemanticInfoSummary = Nothing

            Dim semanticModel = compilation.GetSemanticModel(tree)

            Dim symbolInfo As SymbolInfo

            If True Then
                Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1)
                symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1)

                Assert.NotNull(symbolInfo.Symbol)
                Assert.Equal("Sub X.Add(x As System.String)", symbolInfo.Symbol.ToTestDisplayString())
                Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
                Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
            End If

            If True Then
                Dim node2 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 2)
                symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node2)

                Assert.NotNull(symbolInfo.Symbol)
                Assert.Equal("Sub X.Add(x As System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
                Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
                Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
            End If
        End Sub

J
Jared Parsons 已提交
1622
        <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")>
P
Pilchie 已提交
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
        Public Sub GetCollectionInitializerSymbolInfo_02()
            Dim compilation = CreateCompilationWithMscorlib(
<compilation>
    <file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
 
class X 
    Inherits List(Of Integer)

    Sub Add(x As X)
    End Sub

    Sub Add(x As List(Of Byte))
    End Sub
 
    Shared Sub Main()
        Dim z = new X() From { String.Empty } 'BIND1:"String.Empty"
    End Sub
End Class
    ]]></file>
</compilation>)

            Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
            Dim semanticInfo As SemanticInfoSummary = Nothing

            Dim semanticModel = compilation.GetSemanticModel(tree)

            Dim symbolInfo As SymbolInfo

            Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1)
            symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1)

            Assert.Null(symbolInfo.Symbol)
            Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason)
            Assert.Equal(2, symbolInfo.CandidateSymbols.Length)
            Assert.Equal({"Sub X.Add(x As System.Collections.Generic.List(Of System.Byte))",
                          "Sub X.Add(x As X)"},
                         symbolInfo.CandidateSymbols.Select(Function(s) s.ToTestDisplayString()).Order().ToArray())
        End Sub

J
Jared Parsons 已提交
1664
        <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")>
P
Pilchie 已提交
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
        Public Sub GetCollectionInitializerSymbolInfo_03()
            Dim compilation = CreateCompilationWithMscorlib(
<compilation>
    <file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
 
Class Base
    Implements IEnumerable(Of Integer)
End Class

class X 
    Inherits Base

    Protected Sub Add(x As String)
    End Sub
End Class

class Y
    Shared Sub Main()
        Dim z = new X() From { String.Empty } 'BIND1:"String.Empty"
    End Sub
End Class
    ]]></file>
</compilation>)

            Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
            Dim semanticInfo As SemanticInfoSummary = Nothing

            Dim semanticModel = compilation.GetSemanticModel(tree)

            Dim symbolInfo As SymbolInfo

            Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1)
            symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1)

            Assert.Null(symbolInfo.Symbol)
            Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
            Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
        End Sub

J
Jared Parsons 已提交
1706
        <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")>
P
Pilchie 已提交
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
        Public Sub GetCollectionInitializerSymbolInfo_04()
            Dim compilation = CreateCompilationWithMscorlib(
<compilation>
    <file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
 
class X 
    Inherits List(Of Integer)

    Sub Add(x As String, y As Integer)
    End Sub
 
    Shared Sub Main()
        Dim z = new X() From { {String.Empty, 12} } 'BIND1:"{String.Empty, 12}"
    End Sub
End Class
    ]]></file>
</compilation>)

            Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
            Dim semanticInfo As SemanticInfoSummary = Nothing

            Dim semanticModel = compilation.GetSemanticModel(tree)

            Dim symbolInfo As SymbolInfo

            Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1)
            symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1)

            Assert.NotNull(symbolInfo.Symbol)
            Assert.Equal("Sub X.Add(x As System.String, y As System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
            Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
            Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
        End Sub

J
Jared Parsons 已提交
1743
        <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")>
P
Pilchie 已提交
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
        Public Sub GetCollectionInitializerSymbolInfo_05()
            Dim compilation = CreateCompilationWithMscorlib(
<compilation>
    <file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
 
class X 
    Inherits List(Of Integer)

    Sub Add(x As String, y As Integer)
    End Sub
 
    Shared Sub Main()
        Dim z = new X() From { {String.Empty, 'BIND1:"String.Empty"
                                12} }         'BIND2:"12"
    End Sub
End Class
    ]]></file>
</compilation>)

            Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
            Dim semanticInfo As SemanticInfoSummary = Nothing

            Dim semanticModel = compilation.GetSemanticModel(tree)

            Dim symbolInfo As SymbolInfo

            For i As Integer = 1 To 2
                Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", i)
                symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1)

                Assert.Null(symbolInfo.Symbol)
                Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
                Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
            Next
        End Sub

1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
        <Fact()>
        <WorkItem(12983, "https://github.com/dotnet/roslyn/issues/12983")>
        Public Sub GetCollectionInitializerSymbolInfo_06()
            Dim compilation = CreateCompilationWithMscorlib(
<compilation>
    <file name="a.vb">
Option Strict On

Imports System
Imports System.Collections.Generic

Class C1
    Public Shared Sub Main()
        Dim list1 = new List(Of String)
        Dim list2 = new List(Of String)()
        
        Dim list3 = new List(Of String) With { .Count = 3 }
        Dim list4 = new List(Of String)() With { .Count = 3 }
        
        Dim list5 = new List(Of String)  From { 1, 2, 3 }
        Dim list6 = new List(Of String)() From { 1, 2, 3 }
    End Sub
End Class        
    </file>
</compilation>)

            Dim tree = compilation.SyntaxTrees.Single()
            Dim semanticModel = compilation.GetSemanticModel(tree)

            Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of GenericNameSyntax)().ToArray()
            Assert.Equal(6, nodes.Length)

            For Each name In nodes
                Assert.Equal("List(Of String)", name.ToString())
                Assert.Equal("System.Collections.Generic.List(Of System.String)", semanticModel.GetSymbolInfo(name).Symbol.ToTestDisplayString())
                Assert.Null(semanticModel.GetTypeInfo(name).Type)
            Next
        End Sub

P
Pilchie 已提交
1821 1822
    End Class
End Namespace